NotificationManager.cancel(id) is not working inside a broadcast receiver

后端 未结 6 924
温柔的废话
温柔的废话 2020-12-16 00:49

Android: I am trying to cancel a notification from the notification bar after a package being installed. What I am doing is the following:

 public class MyBr         


        
6条回答
  •  清酒与你
    2020-12-16 01:02

    I was facing the same issue recently. I have managed to solve it.

    So from what i understood.

    1) use the id which is basically a random number to notify and send this same id to the piece of code(reciever/activity...) where you want to cancel it.

    2) When using tags, it seems to not work for me as i was giving one tag to all notifications but with unique id.It worked only on the first tag. so i completely avoided using tags. If you want to use tags, issue unique tags along with unique id and use them both while cancelling.

    So final answer... what i used and what works for me:

    STEP 1:
    int notif_id = (int)(System.currentTimeMillis()%10000);
    
    STEP2: add this id inside the action intent (I am launching an activity where the notification gets cancelled on the action click):
    
                    Intent notificationSettingsIntent = new Intent(context.getApplicationContext(), NotificationSettingsActivity.class);
                    notificationSettingsIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    notificationSettingsIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    notificationSettingsIntent.putExtra("fromNotification",true);
                    notificationSettingsIntent.putExtra("notif_id",notif_id);
                    PendingIntent notificationSettingsActivityPendingIntent = PendingIntent.getActivity(context,notif_id,notificationSettingsIntent,PendingIntent.FLAG_ONE_SHOT);
    
    STEP 3: notify using the id in the step 1 but with no tags
    
    NotificationManagerCompat notificationCompat = NotificationManagerCompat.from(context.getApplicationContext());
    
    notificationCompat.notify(notif_id,notificationBuilder.build());
    

    Now in the Activity which gets opened by my action click, i cancel the notification as:

    NotificationManagerCompat notificationCompat = NotificationManagerCompat.from(context.getApplicationContext());
    
    notificationCompat.cancel(getIntent().getIntExtra("notif_id"));
    

    Works every time now.

提交回复
热议问题