我创建了一项服务,其工作是在用户关闭应用程序时清除通知。一切都运行得很好但是有时,当应用程序在后台运行超过 1 分钟时,服务就会被终止(这意味着通知不会被取消)。
为什么会发生这种情况?我认为停止服务的唯一方法是使用 stopSelf() 或 stopService()。
public class OnClearFromRecentService extends Service {
private static final String TAG = "onClearFromRecentServic";
private NotificationManagerCompat mNotificationManagerCompat;
@Override
public void onCreate() {
super.onCreate();
mNotificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service Started");
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Service Destroyed");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
//Put code here which will be executed when app is closed from user.
Log.d(TAG, "onTaskRemoved was executed ");
if (mNotificationManagerCompat != null) {
mNotificationManagerCompat.cancelAll();
} else {
Log.d(TAG, "onTaskRemoved: mNotifManager is null!");
}
stopSelf();
}
}
我从启动屏幕 Activity 启动服务,如下所示:startService(new Intent(this, OnClearFromRecentService.class));
Also here are some Log messages:
尝试返回START_STICKY形式onStartCommand。
然后系统将尝试重新创建。
check this https://developer.android.com/reference/android/app/Service.html#START_STICKY官方文档。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service Started");
return START_NOT_STICKY;
}
如果您还希望重新传递 Intent,您也可以尝试返回 START_REDELIVER_INTENT。
START_REDELIVER_INTENT
从 onStartCommand(Intent, int, int) 返回的常量:如果这样
服务的进程在启动时被终止(从返回后)
onStartCommand(Intent, int, int)),那么它将被安排为
重新启动,最后一次传递的 Intent 通过再次重新传递给它
onStartCommand(意图,int,int)。
来自文档。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)