主应用程序被终止时的终止通知。
由于您的通知和应用程序是在不同的线程中处理的,因此通过 MultitaskManager 终止您的应用程序不会终止您的通知。正如您已经正确调查的那样,杀死您的应用程序甚至不一定会导致 onExit() 回调。
那么解决办法有哪些呢?
您可以从您的活动中启动服务。特殊服务具有:如果应用程序进程由于某种原因被终止,它们会自动重新启动。因此,您可以通过终止重新启动时的通知来重用自动重新启动。
第1步创建一个杀死的服务简单的一个。它只是杀死创建时的通知并有他特殊的活页夹。
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);
}
}
步骤2:将其添加到您的清单中:将其添加到 标记之间的某个位置。
<service android:name="KillNotificationsService"></service>
步骤3:始终在触发通知之前创建服务,并使用静态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);
重新启动服务可能需要一些时间(1-5 秒),但它最终会启动并终止通知。