我有一个前台服务来下载一些网络内容。
不幸的是,由于一个错误 在这里报告 ,当接收器在我的服务内部接收广播时,我的服务被杀死了,但它的通知不会被杀死,我在我的logcat中看到了以下日志:
I/ActivityManager(449): Killing 11073:my-package-name/u0a102 (adj 0): remove task
当父服务被操作系统杀死时,是否有任何方法可以销毁前台通知?
服务结束后移除前台通知。
@Override
public void onDestroy() {
// mycleanup first
stopForeground(true);
super.onDestroy();
}
@Override
public void onDestroy() {
// as the bug seems to exists for android 4.4
if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT)
{
stopForeground(true);
}
super.onDestroy();
}
or
public void onTaskRemoved (Intent rootIntent)
{
// as the bug seems to exists for android 4.4
if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT)
{
stopForeground(true);
}
}
在通知中,定期检查服务是否仍在运行(例如使用下面的代码:Handler
):
public static boolean isMyServiceRunning(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private static final int DEALY = 10000;
private Handler handler = new Handler();
...
handler.postDelayed(ensureSericeIsRunning, DELAY);
...
private Runnable ensureSericeIsRunning = new Runnable() {
@Override
public void run() {
if (!isMyServiceRunning(getActivity())){
//shut down notification
} else {
handler.postDelayed(ensureSericeIsRunning, DELAY);
}
}
};
onStop
或 onDestroy
中移除通知。但请注意,这并不能保证一定有效。在 API 14 及以上版本中,即使没有前台通知,服务仍然可能在运行。你可以返回 START_STICKY,这将使系统在销毁服务后重新启动它。 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
START_STICKY
也无法在KitKat中重新启动服务!!! - Ali使用onDestroy()
方法。尽管文档中说它不能保证被调用,但我已经测试了多次,唯一不会被调用的情况是系统杀死进程,但在那个时候你的通知也会被杀死,所以没关系。
onTaskRemoved()
内调用stopForground(true)
了吗? - Nikola Despotoski