关于服务的Android文档说:“另一个应用程序组件可以启动一个服务,即使用户切换到另一个应用程序,它也会继续在后台运行。”
假设 Android 服务在 onStartCommand 中生成一个线程或 AsyncTask:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//asyncrhonous call-1
new SomeAsyncTask().execute();
//asynchronous call-2
new Thread(new Runnable(){//some runnable}).start();
//shouldn't service terminate here?
return Service.START_NOT_STICKY;
}
在上面的代码中,立即遇到 onStartCommand
return 语句,因为它前面的两个语句是异步的。在此处生成的线程结束执行之前,服务不应该终止吗?如果它们是非守护进程怎么办?
此外,由于服务(与 IntentService 有点混淆)在 UI 线程上执行,因此我们需要在单独的线程中执行网络操作。因此,人们可能经常需要创建异步任务或不同的线程。任何人都可以帮助我了解服务的执行以及服务是否“继续在后台运行”?那么,从 onStartCommand 返回后,它“运行”什么呢?
最佳答案
So my doubt is that shouldn't the service terminate before the threads spawned here end their execution
没有。 onStopCommand()
返回并不表示服务正在被销毁。
if a service "continue to run in the background",then after returning from onStartCommand, what does it "run"?
默认情况下什么都没有。它只是坐在那里,占用内存,并且对用户来说是一个普遍的麻烦。
如果您启动一项服务,您需要对何时以及如何停止该服务有一个明确的计划。服务可以通过自身调用 stopSelf()
或由其他人调用 stopService()
来停止。
关于java - 从 onStopCommand 返回是否会结束 Android 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21438946/