Notificación de línea múltiple de Android como la aplicación Gmail


Estoy tratando de crear una notificación de varias líneas como lo hace la aplicación Gmail como se muestra en la imagen de abajo (las 5 notificaciones agrupadas en una notificación)

introduzca la descripción de la imagen aquí

He probado varios ejemplos, pero solo parece que puedo crear notificaciones individuales como

   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);
      }

No estoy seguro de cómo crear un grupo de notificaciones al que pueda agregar líneas.

Author: halfer, 2013-12-23

5 answers

Estás buscando "Big View Style", así:

introduzca la descripción de la imagen aquí

Documentación relacionada:

 25
Author: Marcin Orlowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-27 12:44:46
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.
 30
Author: Ganesh Katikar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-29 11:15:52

Aquí tengo la solución: Asegúrese de crear BrodCast Reciever para borrar la pila de matriz cuando la notificación dismiss

    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 se vería así:

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

  }

En el manifiesto Poner esto:

    <receiver
    android:name="your.package.MyBroadcastReceiver"
    android:exported="false" >
    </receiver>
 10
Author: Sufiyan Ansari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-03 10:32:27

Sé que esto se ha preguntado hace mucho tiempo y probablemente muchos usuarios como yo también estaban buscando aquí, pero daré el código completo de notificación de esta manera. Imagine un escenario en el que tiene una aplicación de chat y donde desea obtener notificaciones agrupadas POR CADA USUARIO!aviso por cada usuario. Por lo tanto, la mejor manera de hacerlo es notificar por id de usuario único, por lo que debe escribir un solo código para notificar, ya que no puede adivinar cuántas notificaciones están presentes en ese momento si lo está segmentación por debajo del nivel de API 23, lo que está alejando a casi muchos usuarios de la vista. Entonces, ¿qué debe hacer cuando desea agrupar cada notificación recibida por el usuario y mantener la lógica? La mejor manera que hice que fue el uso de preferencias compartidas con un poco de lógica allí déjame publicar el código con comentarios.

(De esta manera se dirige a las API más bajas para que el KitKat maneje esta lógica también)

La clase que imita la notificación como una prueba.

/**
 * 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 INSTANCE 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();

    }

}
}

El receptor de difusión para eliminar intención. ¡No olvides añadir un receptor a tu manifiesto!

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();
}
}
 5
Author: VA Entertaiment,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-28 05:19:38

Actualmente no hay tal cosa como un "grupo de notificaciones", sino notificaciones individuales con múltiples líneas de texto (como ya se ha señalado esto se hace con el bigContentView, que desea utilizar el Builder para crear). Para actualizar una notificación para agregar más datos, simplemente publícala de nuevo (con el mismo ID y etiqueta) con una cadena más grande en BigTextStyle, o más líneas en InboxStyle.

 0
Author: dsandler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-24 05:58:19