2013-12-23 8 views
27

Ich versuche, eine mehrzeilige Meldung wie die Google Mail-Anwendung zu erstellen ist, wie im Bild unten (die 5 Meldungen gruppiert unter einer Benachrichtigung)Android mehrzeilige Meldung wie Google Mail App

enter image description here

Ich habe gezeigt, verschiedene Beispiele versucht, aber kann nur scheinen einzelne Meldungen wie

public void createSingleNotification(String title, String messageText, String tickerttext) { 
     int icon = R.drawable.notification_icon; // icon from resources 
     CharSequence tickerText = tickerttext; // ticker-text 
     long when = System.currentTimeMillis(); // notification time 
     Context context = getApplicationContext(); // application Context 
     CharSequence contentTitle = title; // expanded message title 
     CharSequence contentText = messageText; // expanded message text 
     Intent notificationIntent = new Intent(this, MainActivity.class); 

     Bundle xtra = new Bundle(); 
     xtra.putString("title", title); 
     xtra.putString("message", messageText); 

     notificationIntent.putExtras(xtra); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
      notificationIntent, PendingIntent.FLAG_ONE_SHOT 
      + PendingIntent.FLAG_UPDATE_CURRENT); 
     String ns = Context.NOTIFICATION_SERVICE; 

     NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 
     Notification notification = new Notification(icon, tickerText, when); 
     notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
     notification.defaults |= Notification.DEFAULT_LIGHTS; 
     notification.defaults |= Notification.DEFAULT_SOUND; 
     notification.defaults |= Notification.FLAG_AUTO_CANCEL; 
     notification.flags = Notification.DEFAULT_LIGHTS 
      | Notification.FLAG_AUTO_CANCEL; 
     final int HELLO_ID = 0; 
     mNotificationManager.notify(HELLO_ID, notification); 
     } 

ich bin nicht sicher zu erstellen, wie eine Benachrichtigungsgruppe erstellen, die ich hinzufügen können Zeilen.

+0

Es sei möglich durch benutzerdefinierte UI http://stackoverflow.com/questions/16168553/create-custom-notification-android – bitsabhi

Antwort

25

Sie sind für "Big Ansicht Style" suchen, wie folgt aus:

enter image description here

Verwandte Dokumentation:

+0

Danke, gut zu wissen, dass es Große Bildschirm Mitteilung genannt wird. Alle Tutorials, die ich finde, erstellen eine Benachrichtigung mit mehreren Zeilen gleichzeitig. Ich möchte eine Möglichkeit, eine Benachrichtigung mit einer einzelnen Zeile zu erstellen und dann bei Bedarf weitere Zeilen hinzuzufügen. – user3013243

+3

Link zu [Big View] (http://developer.android.com/training/notify-user/expanded.html) – Ajoy

0

Es gibt momentan keine solche th als eine "Benachrichtigungsgruppe", sondern einzelne Benachrichtigungen mit mehreren Textzeilen (wie bereits erwähnt, erfolgt dies mit der bigContentView, die Sie mit Builder erstellen möchten). Um eine Benachrichtigung zu aktualisieren, um weitere Daten hinzuzufügen, senden Sie sie einfach erneut (mit derselben ID und demselben Tag) mit einer größeren Zeichenfolge in BigTextStyle oder mehr Zeilen in InboxStyle.

+0

Vielen Dank Ich habe eine BigView-Benachrichtigung mit BigTextStyle erstellt. Ich arbeite an einer Möglichkeit, die in der Benachrichtigung angezeigte Nachricht zu aktualisieren. Ich weiß, dass ich die Benachrichtigung mit der gleichen ID aktualisieren kann. Es gibt jedoch eine Möglichkeit, die aktuell in der Benachrichtigung angezeigte Nachricht zu erhalten und sie als String zu speichern, den ich dann nach Bedarf bearbeiten kann, bevor ich die Benachrichtigung aktualisiere. – user3013243

+2

Nein, Sie müssen diese Daten selbst im Auge behalten. Sobald ein Benachrichtigungsobjekt gepostet wurde, können Sie seinen Inhalt nicht wirklich zurückbekommen. – dsandler

+0

Danke, ich speichere die Daten und erstelle dann bei Bedarf eine Benachrichtigung mit den aktualisierten Daten. – user3013243

25
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) 
    .setSmallIcon(R.drawable.notification_icon) 
    .setContentTitle("Event tracker") 
    .setContentText("Events received") 
NotificationCompat.InboxStyle inboxStyle = 
     new NotificationCompat.InboxStyle(); 

String[] events = {"line 1","line 2","line 3","line 4","line 5","line 6"}; 
// Sets a title for the Inbox in expanded layout 
inboxStyle.setBigContentTitle("Event tracker details:"); 
... 
// Moves events into the expanded layout 
for (int i=0; i < events.length; i++) { 
    inboxStyle.addLine(events[i]); 
} 
// Moves the expanded layout object into the notification object. 
mBuilder.setStyle(inboxStyle); 

... 
// Issue the notification here. 
+1

Also, wo sind die Ereignisse aus dem String-Array leer? – JPM

+0

Schönes Beispiel! Vielen Dank. – t0m

4

Ich weiß, das vor langer Zeit gefragt wurde, und wahrscheinlich viele Nutzer wie ich waren auch hier gesucht, aber ich werde vollständigen Code der Meldung in diesem manner.Imagine Szenario geben, wo Sie eine Chat-Anwendung haben und Wenn Sie möchten, dass Benachrichtigungen von jedem Benutzer gruppiert werden.Beachten Sie am besten, dies zu tun, um mit einer eindeutigen Benutzer-ID zu benachrichtigen, also müssen Sie einen einzigen Code schreiben, um zu benachrichtigen, da Sie nicht erraten können, wie viele Benachrichtigungen vorhanden sind In diesem Moment, wenn Sie unter api Ebene 23 zielen, was fast viele Benutzer außer Sichtweite bringt.Was soll man tun, wenn Sie wollen, dass jeder Benutzer Benachrichtigungen erhält und Logik behält? Das Beste, was ich getan habe, war die Verwendung von gemeinsamen Einstellungen ein wenig Logik dort lassen Sie mich den Code mit Kommentaren veröffentlichen.

(Durch diese Targeting Sie apis zu senken, so dass die kitkat diese Logik zu handhaben wird)

Die Klasse, die die Benachrichtigung als Test imitiert.

/** 
* Simple id just for test 
*/ 
private int NOTIFICATION_ID = 1; 
private static int value = 0; 
Notification.InboxStyle inboxStyle = new Notification.InboxStyle(); 
private NotificationCompat.Builder mCopat; 
private Bitmap bitmap; 
private SharedPreferences sharedPreferences; 
private SharedPreferences.Editor editor; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main2); 
    bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); 
    mCopat = new NotificationCompat.Builder(getApplicationContext()); 

    /** 
    * Here we create shared preferences.Probably you will create some helper class to access shared preferences from everywhere 
    */ 
    sharedPreferences = getSharedPreferences("shared", MODE_PRIVATE); 
    editor = sharedPreferences.edit(); 

    /** 
    * I clear this for test purpose. 
    */ 
    editor.clear(); 
    editor.commit(); 
} 


public void hey(View view) { 

    /** 
    * Add notification,let`s say add 4 notifications with same id which will be grouped as single and after it add the rest which will be grouped as new notification. 
    */ 
    int clickedTime = value++; 
    if (clickedTime == 4) { 
     NOTIFICATION_ID++; 
    } 


    /** 
    * Here is the important part!We must check whether notification id inserted inside the shared preferences or no.If inserted IT MEANS THAT WE HAVE an notification 
    * to where we should add this one (add the new one to the existing group in clear way) 
    */ 
    if (sharedPreferences.getString(String.valueOf(NOTIFICATION_ID), null) != null) { 
     Log.d("fsafsafasfa", "hey: " + "not null adding current"); 

     /** 
     * TAKE A NOTICE YOU MUST NOT CREATE A NEW INTANCE OF INBOXSTYLE,OTHERWISE IT WON`T WORK.JUST ADD VALUES TO EXISTING ONE 
     */ 

     NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
     Notification.Builder builder = new Notification.Builder(this); 
     builder.setContentTitle("Lanes"); 
     builder.setContentText("Notification from Lanes " + value); 
     builder.setSmallIcon(R.mipmap.ic_launcher); 
     builder.setLargeIcon(bitmap); 
     builder.setAutoCancel(true); 

     /** 
     * By this line you actually add an value to the group,if the notification is collapsed the 'Notification from Lanes' text will be displayed and nothing more 
     * otherwise if it is expanded the actual values (let`s say we have 5 items added to notification group) will be displayed. 
     */ 
     inboxStyle.setBigContentTitle("Enter Content Text"); 
     inboxStyle.addLine("hi events " + value); 


     /** 
     * This is important too.Send current notification id to the MyBroadcastReceiver which will delete the id from sharedPrefs as soon as the notification is dismissed 
     * BY USER ACTION! not manually from code. 
     */ 
     Intent intent = new Intent(this, MyBroadcastReceiver.class); 
     intent.putExtra("id", NOTIFICATION_ID); 


     PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); 

     /** 
     * Simply set delete intent. 
     */ 
     builder.setDeleteIntent(pendingIntent); 
     builder.setStyle(inboxStyle); 
     nManager.notify("App Name", NOTIFICATION_ID, builder.build()); 

     /** 
     * Add id to shared prefs as KEY so we can delete it later 
     */ 
     editor.putString(String.valueOf(NOTIFICATION_ID), "notification"); 
     editor.commit(); 
    } else { 

     /*** 
     * Here is same logic EXCEPT that you do create an INBOXSTYLE instance so the values are added to actually separate notification which will just be created now! 
     * The rest logic is as same as above! 
     */ 

     /** 
     * Ok it gone to else,meaning we do no have any active notifications to add to,so just simply create new separate notification 
     * TAKE A NOTICE to be able to insert new values without old ones you must call new instance of InboxStyle so the old one will not take the place in new separate 
     * notification. 
     */ 
     Log.d("fsafsafasfa", "hey: " + " null adding new"); 
     inboxStyle = new Notification.InboxStyle(); 
     NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
     Notification.Builder builder = new Notification.Builder(this); 
     builder.setContentTitle("Lanes"); 
     builder.setContentText("Notification from Lanes " + value); 
     builder.setSmallIcon(R.mipmap.ic_launcher); 
     builder.setLargeIcon(bitmap); 
     builder.setAutoCancel(true); 
     inboxStyle.setBigContentTitle("Enter Content Text"); 
     inboxStyle.addLine("hi events " + value); 

     Intent intent = new Intent(this, MyBroadcastReceiver.class); 
     intent.putExtra("id", NOTIFICATION_ID); 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); 
     builder.setDeleteIntent(pendingIntent); 

     builder.setStyle(inboxStyle); 
     nManager.notify("App Name", NOTIFICATION_ID, builder.build()); 
     editor.putString(String.valueOf(NOTIFICATION_ID), "notification"); 
     editor.commit(); 

    } 

} 

}

Der Rundfunkempfänger zum Löschen intent.Do vergessen Sie nicht, den Receiver mit Ihrem Manifest hinzuzufügen!

public class MyBroadcastReceiver extends BroadcastReceiver { 

/** 
* Receive swipe/dismiss or delete action from user.This will not be triggered if you manually cancel the notification. 
* @param context 
* @param intent 
*/ 
@Override 
public void onReceive(Context context, Intent intent) { 

    /** 
    * As soon as received,remove it from shared preferences,meaning the notification no longer available on the tray for user so you do not need to worry. 
    */ 
    SharedPreferences sharedPreferences = context.getSharedPreferences("shared", context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedPreferences.edit(); 
    editor.remove(String.valueOf(intent.getExtras().getInt("id"))); 
    editor.commit(); 
} 

}

9

Hier ich die Lösung: Vergewissern Sie sicher, brodcast Reciever löschen Feldstapel zu schaffen, wenn Benachrichtigung

static ArrayList<String> notifications = new ArrayList<>(); 

private static void sendNotification(String messageBody,Context cxt) { 

    //onDismiss Intent 
    Intent intent = new Intent(cxt, MyBroadcastReceiver.class); 
    PendingIntent broadcastIntent = PendingIntent.getBroadcast(cxt.getApplicationContext(), 0, intent, 0); 

    //OnClick Listener 
    startWFApplication().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    PendingIntent pendingIntent = PendingIntent.getActivity(cxt, 0, startWFApplication(), 
      PendingIntent.FLAG_ONE_SHOT); 

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(cxt) 
      .setSmallIcon(R.drawable.fevicon) 
      .setContentTitle("Title") 
      .setContentText(messageBody) 
      .setAutoCancel(true) 
      .setSound(defaultSoundUri) 
      .setContentIntent(pendingIntent); 
    NotificationCompat.InboxStyle inboxStyle = 
      new NotificationCompat.InboxStyle(); 
    // Sets a title for the Inbox in expanded layout 
    inboxStyle.setBigContentTitle("Title - Notification"); 
    inboxStyle.setSummaryText("You have "+notifications.size()+" Notifications."); 
    // Moves events into the expanded layout 
    notifications.add(messageBody); 
    for (int i=0; i < notifications.size(); i++) { 
     inboxStyle.addLine(notifications.get(i)); 
    } 
    // Moves the expanded layout object into the notification object. 
    notificationBuilder.setStyle(inboxStyle); 

    NotificationManager notificationManager = 
      (NotificationManager) cxt.getSystemService(Context.NOTIFICATION_SERVICE); 

    notificationManager.notify(0, notificationBuilder.build()); 
    notificationBuilder.setDeleteIntent(broadcastIntent); 
} 
public static Intent startWFApplication(){ 
    Intent launchIntent = new Intent(); 
    launchIntent.setComponent(new ComponentName("your.package", "Yyour.package.servicename")); 
    return launchIntent; 
} 

BroadCastReciever wie folgt aussehen würde entlassen:

public class MyBroadcastReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Notification.notifications.clear(); 
    } 

    } 

Im Manifest Setzen Sie das:

<receiver 
    android:name="your.package.MyBroadcastReceiver" 
    android:exported="false" > 
    </receiver> 
+0

, aber ich denke Benachrichtigungen Liste würde Null, wenn ich App aus den letzten – Ancee

+0

löschen Ich habe über Code, der keine Benachrichtigungen wie Google Mail-App zeigt, wenn ich Nachricht mit FCM concole senden. – Firdosh

+0

Es funktioniert dank :-) aber funktioniert nur, wenn App im Vordergrund nicht funktioniert, wenn App im Hintergrund ist. – Firdosh