当用户通过启动器图标打开应用程序时删除通知图标

Remove notification icon when user open app through launcher Icon

你好,我正在开发一个应用程序,我想在收到短信时向用户发送推送通知。现在的问题是,当用户通过启动器图标打开应用程序时,通知图标仍然没有删除 这是我的代码:

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

我也这样试过:

notificationManager.cancel(0);

也试过这个:

notificationManager.cancelAll();

但这两个都不起作用。他们不允许通知发生。也许他们在创建之前取消了推送通知。 请帮忙!

取消主Activity的onCreate()方法中的所有通知

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

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

那是因为你问了

Remove notification icon when user open app through launcher Icon

但最好的方法是将它放在 onResume() 中,这样当应用程序在后台时,您希望显示通知并在用户将其带到前台时将其删除。

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

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