首页 > 解决方案 > 更新后无法取消通知

问题描述

我正在开发一个倒计时应用程序,目前正在尝试在倒计时运行时退出应用程序时显示通知。相应地,我希望在用户返回应用程序时通知消失。

到目前为止,我已经设法使它适用于带有静态文本的简单通知,请执行以下操作:在 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();
    }
}

标签: javaandroidservicenotificationscountdowntimer

解决方案


它可以通过多种方式处理,你没有停止你的计时器

注意:- 在 Kotlin 中发布代码

1)

override fun onDestroy() {
   counter.cancel()
}
  1. 在你的活动中
覆盖有趣的 onResume() {
    超级.onResume()
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) 作为 NotificationManager
     notificationManager.cancelAll()
}

推荐阅读