首页 > 解决方案 > 无法清除通知并从通知中打开片段

问题描述

我正在尝试清除通知。但它仍然存在。无法从通知中打开片段活动。下面是我的代码,

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int sticky;

        try {
            AndroidLogger.log(5, TAG, "Missed call notification on start");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
                NotificationChannel channel = new NotificationChannel("1", "Call Notification", importance);
                channel.setDescription("Get alert for missed call");
                channel.setShowBadge(true);
                channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                NotificationManager notificationManager = getSystemService(NotificationManager.class);
                notificationManager.createNotificationChannel(channel);
            }
            Intent notifyIntent = new Intent(this, ViewFragment.class);
            notifyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


            PendingIntent pIntent = PendingIntent.getActivity(this, 0, notifyIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
                    .setSmallIcon(R.drawable.nexge_logo)
                    .setContentTitle("Missed Call")
                    .setContentText(intent.getStringExtra("Number"))
                    .setContentIntent(pIntent)
                    .setAutoCancel(true)
                    .setPriority(Notification.PRIORITY_MAX);

            Notification buildNotification = mBuilder.build();
            NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            //mNotifyMgr.notify(1, buildNotification);

            startForeground(1,buildNotification);
        } catch (Exception exception) {
            AndroidLogger.error(1, TAG, "Exception while starting service", exception);
        }
        return START_NOT_STICKY;
    }
}

任何人都可以帮我解决这个问题。提前致谢。以下是我没有得到正确答案的另一个问题。帮我解决一下 关于android中未接来电的通知

标签: javaandroidandroid-studionotificationsfragment

解决方案


我对类似问题的解决方案是将 PendingIntent Flag 更改为 PendingIntent.FLAG_ONE_SHOT 从 Android 文档:

指示此 PendingIntent 只能使用一次的标志。用于 getActivity(Context, int, Intent, int)、getBroadcast(Context, int, Intent, int) 和 getService(Context, int, Intent, int)。

如果设置,则在调用 send() 后,它将自动为您取消,并且将来通过它发送的任何尝试都将失败。

并添加通知 FLAG_AUTO_CANCEL 标志:

mBuilder.flags |= Notification.FLAG_AUTO_CANCEL;

这应该确保通知一旦使用就会被删除。

编辑:应该打电话

Notification notification = mBuilder.build();

首先,然后

notification.flags = Notification.FLAG_AUTO_CANCEL;

Edit2:刚刚注意到您正在使用通知startForeground()。这意味着只要您的服务/活动正在运行,通知就会一直存在(这是默认设置,因此用户会知道有一个服务/活动仍在运行)。

只要您的服务/活动确实作为前台服务运行,通知就会一直存在。


推荐阅读