Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove notification icon when user open app through launcher Icon

Hello I am developing an app in which i want to give push notifications to user when Sms receives. Now the problem is that the notification icon still does not remove when app open by user through launcher icon Here is my code:

NotificationCompat.Builder notify = new NotificationCompat.Builder(context);
            notify.setSmallIcon(R.drawable.appicon);
            notify.setContentTitle(title);
            notify.setContentText(msgBody);
            notify.setAutoCancel(true);
            Notification notification = new Notification();
            notification.defaults |= Notification.DEFAULT_VIBRATE;

            //notify.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
            notify.setLights(Color.GREEN, 2000, 2000);
            notify.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            Intent notificationIntent = new Intent(Intent.ACTION_MAIN);
            notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
            notificationIntent.setType("vnd.android-dir/mms-sms");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent intentt = PendingIntent.getActivity(context, 0,notificationIntent, 0);
            notify.setContentIntent(intentt);
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notify.build());

I tried like this too:

notificationManager.cancel(0);

and also tried this:

notificationManager.cancelAll();

but both these doesnot work. They doesnot allow notification to occur. Maybe they are cancelling the push notification before its creation. Please Help!

like image 413
Arslan Ali Avatar asked Dec 03 '22 14:12

Arslan Ali


1 Answers

Just cancel all the notifications inside the main Activity's onCreate() method

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

That is because you asked

Remove notification icon when user open app through launcher Icon

But best way is to put it in onResume() so that when the app is in background you want to show the notification and remove it when user brings it to foreground.

@Override
protected void onResume() {
    super.onResume();

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}
like image 186
Archie.bpgc Avatar answered Dec 06 '22 12:12

Archie.bpgc