Android 停止 IntentService 的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10250745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Proper way to stop IntentService
提问by malinjir
I'm using an IntentService to upload images to a server. My problem is that I don't know how/when to stop the service. When I call stopself() in onHandleIntent(Intent ..) all Intents which are waiting in the IntentService queue are removed. But I don't want to stop the service from an activity because I want to complete upload proccess even if my application is not running.
我正在使用 IntentService 将图像上传到服务器。我的问题是我不知道如何/何时停止服务。当我在 onHandleIntent(Intent ..) 中调用 stopself() 时,所有在 IntentService 队列中等待的 Intent 都会被删除。但是我不想从活动中停止服务,因为即使我的应用程序没有运行,我也想完成上传过程。
回答by CommonsWare
My problem is that I don't know how/when to stop the service.
我的问题是我不知道如何/何时停止服务。
IntentService
automatically stops itself when onHandleIntent()
ends, if no more commands had been sent to it while onHandleIntent()
was running. Hence, you do not manually stop an IntentService
yourself.
IntentService
onHandleIntent()
如果onHandleIntent()
在运行时没有向它发送更多命令,则在结束时自动停止。因此,您不会IntentService
自己手动停止。
When I call stopself() in onHandleIntent(Intent ..) all Intents which are waiting in the IntentService queue are removed.
当我在 onHandleIntent(Intent ..) 中调用 stopself() 时,所有在 IntentService 队列中等待的 Intent 都会被删除。
Which is why you do not do that.
这就是为什么你不这样做。
But I don't want to stop the service from an activity because I want to complete upload proccess even if my application is not running.
但是我不想从活动中停止服务,因为即使我的应用程序没有运行,我也想完成上传过程。
Then you let the IntentService
stop itself.
然后你让IntentService
停止本身。
回答by techiServices
An IntentService
stops itself when it has no more Intent
s (jobs) to process. It runs stopSelf(startId)
for each Intent
(job). Have a look at the IntentService
source or the Extending the Service Class
from here http://developer.android.com/guide/topics/fundamentals/services.html
一个IntentService
停止本身时,它没有更多的Intent
S(作业)来处理。它stopSelf(startId)
为每个Intent
(作业)运行。查看IntentService
源代码或Extending the Service Class
从这里http://developer.android.com/guide/topics/fundamentals/services.html