【问题标题】:How to clear notification on notification action click?如何清除通知操作点击的通知?
【发布时间】:2018-02-24 14:10:55
【问题描述】:

我正在开发一个 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());

【问题讨论】:

标签: java android notifications


【解决方案1】:

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

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()中调用它

【讨论】:

    猜你喜欢
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多