服务被杀死时销毁前台通知

我有一个前台服务从网上下载一些内容。

不幸的是,由于在这里报告的错误,我的服务在接收器收到我的服务中的广播时被杀死,但它的通知不会被杀死,我在logcat中看到以下日志:

I/ActivityManager(449): Killing 11073:my-package-name/u0a102 (adj 0): remove task 

无论如何,当它的父服务被OS杀死时,是否要销毁前台通知?

服务结束删除前台通知。

 @Override public void onDestroy() { // mycleanup first stopForeground(true); super.onDestroy(); } 

使用stopForeground:

 @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(); } 

要么

 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); } } }; 

使用onDestroy() 。 即使文档说它不能保证被调用,我已经多次测试,并且唯一没有被调用的情况是系统终止进程,但到那时你的通知将被杀死,所以没关系。

您可以从服务类内部的onStoponDestroy删除通知。 PS没有保证这会工作,在api 14及以上服务即使没有前台通知仍然可以运行,你可以返回START_STICKY,即使系统销毁它也会带回你的服务,系统会重启它。

  @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } 

使用服务onTaskRemoved()方法。