简体   繁体   English

如何清除通知操作点击的通知?

[英]How to clear notification on notification action click?

I'm developing an android app where I display notifications with actions.我正在开发一个 android 应用程序,我在其中显示带有操作的通知。 But on action click notification not clearing, It stuck in that shade.但是在操作点击通知未清除时,它卡在那个阴影中。 How do I clear a notification on action click?如何清除操作点击通知?

MY CODE我的代码

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

Hiding notifications should be processed in the place where the intent is sent.隐藏通知应该在发送意图的地方处理。 In your current code:在您当前的代码中:

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

And in your activity smth like this, to check if it should remove notification:并在您的活动中像这样,检查它是否应该删除通知:

 @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
        }
    }

Depends on what you want, maybe it will be better to call that not in onCreate() but onStart()取决于你想要什么,也许最好不要在onCreate()而是在onStart()调用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM