How, by clicking on the notification, delete the notification and do not open the application?

Asked

Viewed 176 times

4

I need to send a notification but would like when the user clicks on the notification it is deleted and does not open the application

The part of generating the notification that is already working the failed to lock the application not to be opened.

Grateful.

2 answers

3

So that the notification does not launch any Activity(Intent) when clicked create the Pendigintent, passed to the method setContentIntent() of Notificationcompat.Builder, as follows:

PendingIntent resultPendingIntent = PendingIntent.getActivity(context,  0, new Intent(), 0);

Replace the 0 the values you want to use. The important thing is to pass new Intent() in the third parameter.

To delete notification when clicked use setAutoCancel(true) when building the notification.

0

Create the notification:

private void sendNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.drawable.ic_stat_name);
    builder.setContentTitle("My title");
    builder.setContentText("Content Text");
    Intent removeNotifivationIntent = new Intent();
    removeNotifivationIntent.setAction(REMOVE_NOTIFICATION);
    PendingIntent removeNotifivationPendingIntent = PendingIntent.getBroadcast(this, 0, removeNotifivationIntent, 0);
    builder.setContentIntent(removeNotifivationPendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, builder.build());
}

Create a Broadcastreceiver, can be in Oncreate:

    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (REMOVE_NOTIFICATION.equals(action)) {
                String ns = Context.NOTIFICATION_SERVICE;
                NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
                nMgr.cancel(NOTIFICATION_ID);
            }
        }
    };
    registerReceiver(receiver, filter);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.