java无法在更新通知后取消通知
我正在开发一个倒计时应用程序,目前正在尝试在倒计时运行时退出应用程序时显示通知。相应地,我希望在用户返回应用程序时通知消失
到目前为止,我已经成功地使其适用于带有静态文本的简单通知,请执行以下操作:在MainActivity中。java,在onStop()中,我创建了一个intent,并使用startService(intent)启动服务。对称地,在onStart()中,我运行stopService(intent),这样当你返回应用程序时,服务就会被取消。这就像一个符咒,通知会在必要时出现和消失
下一步是尝试让通知显示一个不同的文本(它将显示“剩余X分钟”)。根据那里的信息,要更新现有通知,你必须创建一个新通知,给它与现有通知相同的ID,然后调用。通知通知经理。当我这样做时,通知确实得到了正确的更新(文本按预期更改),但是:现在,返回到主活动并不会取消通知。图标保持在上面,不会被打断
我已经努力解决这个问题好几个小时了。我也尝试过一些黑客行为,比如通过共享首选项发送信号,告诉服务停止,但出于某种原因,它似乎也完全忽略了stopself()命令
有人对原因有什么建议吗?任何帮助都将不胜感激。以下是相关代码:
主要活动。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();
}
}
共 (0) 个答案