在我的 Android 项目中,我需要启动一个 Service
来:
- 即使在应用程序关闭后仍保持 Activity 状态
- 不阻塞主线程
我分析了这个问题的服务、IntentServices 和线程:
使用服务
并覆盖
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Some nasty code
return START_STICKY;
}
我实现了第一个目标,但是当我启动服务时我阻塞了主线程
使用IntentService
并覆盖
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
protected void onHandleIntent(Intent intent) {
// Same nasty code as before
}
我实现了第二个目标,因为我没有阻止 UI,但当我终止应用程序时服务就会终止。
然后我尝试使用 Service
启动一个Thread
,如下所示:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//The usual nasty code
}
});
thread.start();
return START_STICKY;
}
我得到了与第一种情况相同的结果(我阻止了 UI)。
我使用 myActivity.startService(myActivity, MyService.class) 启动服务
我是否遗漏了一些明显的东西?有没有办法同时实现这两个目标?
最佳答案
对于本例:
Stays alive even after the application closure.
你需要使用Service
而不是IntentService
,因为IntentService
总是在onHandleIntent
中的代码之后杀死自己被彻底处决。通过在Service
的onStartCommand
方法中调用startForeground(int notification_id, Notification notification)
,将使您的Service
仍然活着而不阻塞 UI 线程。但是您需要为 startForeground
方法创建一个通知。完成 Service< 后,不要忘记在
。请记住,如果您要执行的代码是异步的,请创建一个扩展 Service
的 onDestroy()
方法中调用 stopForeground(true)
/Handler
的私有(private)类 ServiceHandler
,并在 handleMessage
方法中运行代码。
实现此模式的应用程序是 DU Battery Saver。
关于java - 应用程序关闭后仍保持 Activity 状态且不会锁定 UI 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895471/