Android中服务分为前台服务和后台服务。
前台服务需要通知用户一个Notification,表示用户正式使用该服务;
后台服务运行在后台,不需要通知用户启动了该服务。
然后后台服务在空闲状态被终止,打印如下:
system_process W/ActivityManager: Stopping service due to app idle: u0a66 -1m44s91ms com.ad.demo /.demo.DemoService
com.ad.demo I/DemoService: onDestroy
说明:当应用程序不再前台显示的时候,或者应用程序被关闭的时候,或者系统资源不足的时候,Android系统将后台服务kill掉了。
尝试1:网上找到的一种方法,在服务onStartCommand中返回START_FLAG_RETRY,但是无效。服务并没有重启。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG,"onStartCommand");
new InitSocketThread().start();
flags = Service.START_FLAG_RETRY;
//flags = START_STICKY;
return super.onStartCommand(intent, flags, startId);
//return START_STICKY;
}
尝试2:在onDestroy重启服务:
1.在AndroidManifest.xml中,增加重启服务的广播;
2.在onDestroy()中发送重启的广播,收到广播后,启动服务。
发现报错:
Not allowed to start service Intent { cmp=com.ad.demo/.demo.Demo Service }: app is in background uid UidRecord
尝试3:使用JobIntentService替换Service
public class DemoService extends JobIntentService{
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, CarMultiScreenService.class, JOB_ID, work);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
Log.i(TAG,"onHandleWork");
}
}
//启动服务
DemoService .enqueueWork(context,new Intent());
发现报错:
JobServiceContext: Time-out while trying to bind 1725d35 #u0a66/1 com.ad.carlauncher/.socket.CarMultiScreenService, dropping.
解决方法:去掉原来的:
// @Nullable
// @Override
// public IBinder onBind(Intent intent) {
// return null;
// }
但是,JobIntentService只适合执行特定的任务,在onHandleWork执行完任务后,就执行onDestroy退出了。
本文探讨了Android中后台服务的生存策略,包括前台服务与后台服务的区别,以及尝试使用START_FLAG_RETRY、广播重启和JobIntentService的方法,并最终推荐使用WorkManager来维持服务持久运行。
9912

被折叠的 条评论
为什么被折叠?



