如何清除通知操作的通知单击



我正在开发一个Android应用程序,其中显示了使用操作的通知。但是在动作时,请单击通知未清除,它停留在那个阴影中。我如何清除动作单击的通知?

我的代码

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
PendingIntent openSettingsActivity = PendingIntent.getActivity(this,1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notificationBuilder.addAction(R.drawable.ic_notification_button, "Settings", openSettingsActivity);
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setContentTitle(title);
                notificationBuilder.setContentText(text);
                notificationBuilder.setAutoCancel(true);
                notificationBuilder.setColor(color);
                notificationBuilder.setSmallIcon(R.drawable.ic_notification);
                notificationBuilder.setContentIntent(openSettingsActivity);
                final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notificationBuilder.build());

隐藏通知应在发送意图的位置处理。在您当前的代码中:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
intent.putExtra("hide_notification", true); //add boolean to check later in activity if it should remove notification on activity create

在您的活动中,像这样的活动中检查是否应删除通知:

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //check for notification remove
        boolean hideNotification = getIntent().getBooleanExtra("hide_notification", false);
        if (hideNotification) {
            NotificationManagerCompat nmc = NotificationManagerCompat.from(this);
            nmc.cancel(1); //1 - is your notification id
        }
    }

取决于您想要什么,也许最好在onCreate()中调用它,而是onStart()

最新更新