java - 无法清除通知并从通知中打开片段
问题描述
我正在尝试清除通知。但它仍然存在。无法从通知中打开片段活动。下面是我的代码,
@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中未接来电的通知
解决方案
我对类似问题的解决方案是将 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()
。这意味着只要您的服务/活动正在运行,通知就会一直存在(这是默认设置,因此用户会知道有一个服务/活动仍在运行)。
只要您的服务/活动确实作为前台服务运行,通知就会一直存在。
推荐阅读
- java - 如何修复 Gradle Build 中的“无法处理 kafka-clients-1.1.1.jar”错误
- assembly - 如何在此汇编代码中找到错误?
- html - 视频无法在 iPhone 上播放
- dart - 如何裁剪小部件,或切出特定大小的小部件的正方形部分?
- mysql - 修改后的 DB_TRX_ID 隐藏字段是否会比它使用的要小?
- php - 如何在没有 CTE 的情况下从 sql 查询生成分层结果(谱系)?
- c# - 如何向控件绑定的对象发送事件?
- c# - 如何将 async/await 与循环无穷大一起使用?
- python - 无法同时运行后台线程和加载 wx GUI
- typescript - 将变量用作函数时的编译器错误