【问题标题】:Remove notification icon when user open app through launcher Icon当用户通过启动器打开应用程序时删除通知图标
【发布时间】:2016-05-16 16:59:19
【问题描述】:

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

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

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

【问题讨论】:

  • 您是否尝试将取消代码放在 onCreate 中?
  • @MorZa 不,先生,我也需要吗?但是如果我写了那个并且如果没有通知并且我打开我的应用程序那么它可能会给出空异常?请解释
  • 在我的代码中,我得到了意图,然后检查它是否为空: Intent intent = getIntent();如果(意图!= null){...}。将它放在 onCreate 或 onResume 对我来说是有意义的,因为用户在按下通知时打开应用程序并调用这些方法。

标签: android push-notification sms launcher


【解决方案1】:

只需取消主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();
}

那是因为你问了

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

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

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

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

【讨论】:

  • 我认为onStart 将是这里的最佳选择。 p.s.对于 Kotlin:(getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager)?.cancelAll()
猜你喜欢
  • 1970-01-01
  • 2014-10-29
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 2015-04-07
  • 1970-01-01
相关资源
最近更新 更多