Am正在基于计时器的应用程序上工作,在该应用程序中,计时器开始运行时会显示通知。我将其设置为正在进行中,以便无法清除。
在某些情况下,我使用了cancelAll()方法,但效果很好,但是当我强制关闭应用程序时,通知仍然显示并且无法删除,并尝试在onDestroy()方法中使用该方法,但问题仍然存在。
这是我的代码,并在另一个类中创建了频道:
DependencyProperty
答案 0 :(得分:0)
我曾经发现solution很棒,我会在这里重新输入
由于您的应用程序和通知是在不同的线程中处理的,因此杀死您的应用程序不会杀死该通知。解决方案是创建一个Service
来终止通知,因为当应用突然被终止时,服务会自行重启,因此您可以使用自动重启来终止该通知。
创建服务类
public class KillNotificationsService extends Service {
public class KillBinder extends Binder {
public final Service service;
public KillBinder(Service service) {
this.service = service;
}
}
public static int NOTIFICATION_ID = 666;
private NotificationManager mNM;
private final IBinder mBinder = new KillBinder(this);
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
@Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNM.cancel(NOTIFICATION_ID);
}
}
将其添加到您的清单
<service android:name="KillNotificationsService"></service>
始终在触发通知之前创建服务,并使用静态的Notificationid
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder binder) {
((KillBinder) binder).service.startService(new Intent(
MainActivity.this, KillNotificationsService.class));
Notification notification = new Notification(
R.drawable.ic_launcher, "Text",
System.currentTimeMillis());
Intent notificationIntent = new Intent(MainActivity.this,
Place.class);
PendingIntent contentIntent = PendingIntent.getActivity(
MainActivity.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(),
"Text", "Text", contentIntent);
NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNM.notify(KillNotificationsService.NOTIFICATION_ID,
notification);
}
public void onServiceDisconnected(ComponentName className) {
}
};
bindService(new Intent(MainActivity.this,
KillNotificationsService.class), mConnection,
Context.BIND_AUTO_CREATE);