Cómo descartar una notificación después de hacer clic en la acción


Desde el nivel de API 16 (Jelly Bean), existe la posibilidad de agregar acciones a una notificación con

builder.addAction(iconId, title, intent);

Pero cuando agrego una acción a una notificación y se presiona la acción, la notificación no va a ser desestimada. Cuando se hace clic en la notificación en sí, se puede descartar con

notification.flags = Notification.FLAG_AUTO_CANCEL;

O

builder.setAutoCancel(true);

Pero obviamente, esto no tiene nada que ver con las acciones asociadas a la notificación.

Alguna pista? ¿O esto todavía no forma parte de la API? Lo hice no encontrar nada.

Author: Sufian, 2012-08-09

6 answers

Cuando llamaste a notify en el administrador de notificaciones le diste un id - ese es el id único que puedes usar para acceder a él más tarde (esto es desde el administrador de notificaciones:

notify(int id, Notification notification)

Para cancelar, usted llamaría:

cancel(int id)

Con el mismo id. Así que, básicamente, es necesario realizar un seguimiento de la id o, posiblemente, poner el id en un paquete que añadir a la Intención dentro de la PendingIntent?

 126
Author: Kaediil,
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
2012-08-09 13:15:23

Descubrió que esto era un problema al usar la notificación de visualización Heads Up de Lollipop. Ver directrices de diseño. Aquí está el código completo (ish) para implementar.

Hasta ahora, tener un botón 'Descartar' era menos importante, pero ahora está más en tu cara.

notificación de heads up

Elaboración de la Notificación

int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, context);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setPriority(NotificationCompat.PRIORITY_MAX) //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads Up Display Style
        .setDefaults(Notification.DEFAULT_ALL) // also requires VIBRATE permission
        .setSmallIcon(R.drawable.ic_action_refresh) // Required!
        .setContentTitle("Message from test")
        .setContentText("message")
        .setAutoCancel(true)
        .addAction(R.drawable.ic_action_cancel, "Dismiss", dismissIntent)
        .addAction(R.drawable.ic_action_boom, "Action!", someOtherPendingIntent);

// Gets an instance of the NotificationManager service
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

// Builds the notification and issues it.
notifyMgr.notify(notificationId, builder.build());

NotificationActivity

public class NotificationActivity extends Activity {

    public static final String NOTIFICATION_ID = "NOTIFICATION_ID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
        finish(); // since finish() is called in onCreate(), onDestroy() will be called immediately
    }

    public static PendingIntent getDismissIntent(int notificationId, Context context) {
        Intent intent = new Intent(context, NotificationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(NOTIFICATION_ID, notificationId);
        PendingIntent dismissIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return dismissIntent;
    }

}

AndroidManifest.xml (atributos necesarios para evitar que SystemUI enfoque hacia atrás stack)

<activity
    android:name=".NotificationActivity"
    android:taskAffinity=""
    android:excludeFromRecents="true">
</activity>
 56
Author: aaronvargas,
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-09-19 14:40:15

Descubrí que cuando usas los botones de acción en las notificaciones expandidas, tienes que escribir código adicional y estás más restringido.

Debe cancelar manualmente su notificación cuando el usuario haga clic en un botón de acción. La notificación solo se cancela automáticamente por la acción predeterminada.

Además, si inicia un receptor de transmisión desde el botón, el cajón de notificaciones no se cierra.

Terminé creando una nueva NotificationActivity para abordar estos problemas. Esta actividad intermedia sin ninguna interfaz de usuario cancela la notificación y luego inicia la actividad que realmente quería comenzar desde la notificación.

He publicado un código de ejemplo en una publicación relacionada Al hacer clic en Acciones de notificación de Android no se cierra el cajón de notificaciones.

 15
Author: Vicki,
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
2017-05-23 11:47:28

Siempre puedes cancel() el Notification de lo que sea que esté siendo invocado por la acción (por ejemplo, en onCreate() de la actividad vinculada al PendingIntent que suministras a addAction()).

 5
Author: CommonsWare,
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
2012-08-09 12:44:27

En mi opninion usar un BroadcastReceiver es una forma más limpia de cancelar una Notificación:

En AndroidManifest.xml:

<receiver 
    android:name=.NotificationCancelReceiver" >
    <intent-filter android:priority="999" >
         <action android:name="com.example.cancel" />
    </intent-filter>
</receiver>

En el archivo java:

Intent cancel = new Intent("com.example.cancel");
PendingIntent cancelP = PendingIntent.getBroadcast(context, 0, cancel, PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Action actions[] = new NotificationCompat.Action[1];


NotificationCancelReceiver

public class NotificationCancelReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Cancel your ongoing Notification
    };
}
 5
Author: Himanshu Khandelwal,
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
2015-09-14 18:22:09

Simplemente ponga esta línea :

 builder.setAutoCancel(true);

Y el código completo es :

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.misti_ic));
    builder.setContentTitle("Notifications Title");
    builder.setContentText("Your notification content here.");
    builder.setSubText("Tap to view the website.");
    Toast.makeText(getApplicationContext(), "The notification has been created!!", Toast.LENGTH_LONG).show();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    builder.setAutoCancel(true);
    // Will display the notification in the notification bar
    notificationManager.notify(1, builder.build());
 0
Author: Hanisha,
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-03-13 13:14:55