【问题标题】:How to cancel notification inside onResume()如何取消 onResume() 中的通知
【发布时间】:2015-07-15 11:33:17
【问题描述】:

当有新消息到达时,我的应用会推送通知。一切正常。当用户点击通知时,它按预期恢复Activity,通知被取消(删除)。

但是,当用户重新打开应用(不是通过通知)时,通知仍然保留在状态栏中。

所以,我想取消ActivityonResume() 方法内的通知。

这是创建通知时的代码:

Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
        .setContentTitle(channel + ": Unread messages")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setAutoCancel(true)
        .setContentIntent(intent)
        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.FLAG_AUTO_CANCEL);
notificationManager.notify(0, notification.build());

【问题讨论】:

    标签: android android-intent notifications android-pendingintent


    【解决方案1】:

    你可以用这个:

    public void clearNotification() {
          NotificationManager notificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
          notificationManager.cancel(0);
    }
    

    然后,在 onResume() 方法中调用clearNotification()

    在上面的代码中,0 是你的NOTIFICATION_ID

    【讨论】:

      【解决方案2】:

      只需调用 notificationManager.cancel(id) 将其删除。 当您显示通知时,您指定其 ID(当前设置为 0) - 当您想取消它时,您需要使用相同的 ID。

      【讨论】:

        【解决方案3】:

        NotificationManager.notify() 中的第一个参数是一个标识符,你可以使用它来cancel 之后的通知:

        private static final int NOTIFICATION_ID = 0;
        ...
        notificationManager.notify(NOTIFICATION_ID, notification.build());
        ...
        notificationMananger.cancel(NOTIFICATION_ID);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-03
          相关资源
          最近更新 更多