java - 更新后无法取消通知
问题描述
我正在开发一个倒计时应用程序,目前正在尝试在倒计时运行时退出应用程序时显示通知。相应地,我希望在用户返回应用程序时通知消失。
到目前为止,我已经设法使它适用于带有静态文本的简单通知,请执行以下操作:在 MainActivity.java 中,在 onStop() 中,我创建了一个意图并使用 startService(intent) 启动服务。对称地,在 onStart() 中,我运行 stopService(intent) 以便当您返回应用程序时,服务会被取消。这就像一个魅力,通知出现并在必要时消失。
下一步是尝试让通知显示不同的文本(它将显示“剩余 X 分钟”)。根据那里的信息,要更新现有通知,您必须创建一个新通知,为其提供与现有通知相同的 ID,然后调用 NotificationManager 的 .notify。当我这样做时,通知确实会正确更新(文本按预期更改),但是:现在,返回主要活动不会取消通知。图标停留在那里,不会被打断。
我一直在努力解决这个问题好几个小时。我也尝试过一些技巧,比如通过共享首选项发送信号来告诉服务停止,但由于某种原因,它似乎也完全忽略了命令 stopself()。
有没有人建议可能是什么原因?任何帮助将不胜感激。以下是相关代码:
MainActivity.java:
@Override
protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(getBaseContext(), CounterService.class);
stopService(serviceIntent);
}
protected void onStop() {
super.onStop();
Intent serviceIntent = new Intent(getBaseContext(), CounterService.class);
startService(serviceIntent);
}
计数器服务.java:
public class CounterService extends Service {
Notification notification;
NotificationManager notificator;
Intent intentNoti;
CountDownTimer counter;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
intentNoti = new Intent(this, MainActivity.class);
final PendingIntent pending = PendingIntent.getActivity(this, 0, intentNoti, 0);
final Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.common_full_open_on_phone);
//Countdown
counter = new CountDownTimer (30000, 1000) {
public void onTick(long millisUntilFinished) {
String time = String.valueOf(System.currentTimeMillis());
notification = new Notification.Builder(CounterService.this)
.setContentTitle("Name")
.setContentText(time)
.setSmallIcon(R.drawable.icon_start)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pending)
.setOngoing(true).build();
notificator = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificator.notify(1001, notification);
}
public void onFinish() {
}
}.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
counter.cancel();
}
}
解决方案
它可以通过多种方式处理,你没有停止你的计时器
注意:- 在 Kotlin 中发布代码
1)
override fun onDestroy() {
counter.cancel()
}
- 在你的活动中
覆盖有趣的 onResume() { 超级.onResume() val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) 作为 NotificationManager notificationManager.cancelAll() }
推荐阅读
- c++ - 错误 Windows 标头需要 winnt.h 上的默认打包选项
- bazel - Bazel 链接库:如何更改为链接到已构建库?
- android - firebase 数据库仅在读写设置为 true 时工作
- node.js - 有没有办法修复节点中的这个 Mailchimp API 错误?
- c# - .Net Core C# 将方法/类作为子进程执行
- excel - 代码没有将值粘贴在上面的空行上
- postgresql - 执行 PostgreSQL 存储过程时出现问题
- ios - Widget 扩展、SwiftUI、快照测试
- interbase - 跨库域修改
- php - Gettext 不起作用我做错了什么?