我有一个从服务执行的 AsyncTask
。由于 AsyncTask
在单独的线程中运行,我几乎没有怀疑:
如果服务
onStartCommand()
方法在执行 AsyncTask 时返回,会发生什么情况?执行AsyncTask
时服务是否关闭? 如何最好地解决这种情况?我应该使用 START_STICKY 吗?由于
onPostExecute()
在 UIThread 上运行,它会在与服务的onStartCommand
方法相同的线程上运行吗?如果AsyncTask
在服务关闭时仍在运行,在上述情况下会发生什么。onPostExecute()
将基于哪个线程?
更新:
我使用 Service 的原因是因为 Service 是从 Broadcast Receiver 的 onReceive
方法实例化的。我同意我可以在 onReceive 中使用一个普通线程,但 service-AsyncTask 模式似乎更好,因为我还需要触发一些通知,而我在 onPreExecute
和 onPostExecute
.
最佳答案
I have an AsyncTask executed from a service
因为您很少需要在 Service
中的主应用程序线程上工作,所以我建议只使用普通线程。
What would happen if service onStartCommand() method returns while the AsyncTask is executed ?
没有。
Does the service shut down while AsyncTask is executed ?
onStartCommand()
在向服务发送命令时调用。关闭服务时不会调用它。
should I use START_STICKY ?
这不可能抽象地回答。如果您需要稍后重新启动服务(例如,当可用内存增加时),请使用它。
Since onPostExecute() runs on UIThread, Will it run on same thread as service ?
对象不在 Java 中的线程上运行。因此,服务不在线程上运行。方法在线程上运行。
What would happen in above case if AsyncTask is still running while service shuts down.
这取决于您,因为您是唯一关闭该服务的人。
如果操作系统出于其他原因摆脱服务,它往往会通过终止整个进程来实现,在这种情况下,AsyncTask
也会消失。
Which thread would onPostExeucte() upon ?
onPostExecute()
在主应用程序线程上运行。由于这在 Service
中很少需要,甚至不是一个好主意,请考虑使用普通线程而不是 AsyncTask
。
更好的是,使用 IntentService
,如果您的工作本质上是事务性的(例如,需要运行几秒钟,然后工作完成并且不再需要该服务),因为 IntentService
有自己的后台线程,所以你不需要你的。
更新
The reason I am using Service is because Service is instantiated from a onReceive method of a Broadcast Receiver
这与任何事情都无关。
I need to fire some notifications as well which I am doing in onPreExecute and onPostExecute.
您可以从后台线程引发Notification
。您不需要从主应用程序线程执行此操作。
关于android - 从 Service 执行的 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19439295/