如何在 onHandleIntent() 完成时不结束 Android IntentService?
我启动一个 IntentService。在 onHandleIntent() 中,我使用处理程序发出 HTTP 请求,该处理程序在请求完成时调用,如下所示:
public function onHandleIntent(){
makeRequest("http://somehthing.com", new Handler(){
doStuff();
});
}
onHandleIntent() 在 HTTP 请求返回之前立即完成。请求确实返回,但 ServiceIntent 线程已被销毁,并且 doStuff() 从未运行。
使用 ServiceIntent 处理此类回调处理程序结构的最佳方法是什么?
I start an IntentService. In onHandleIntent() I make an HTTP request with a Handler that is called when the request completes, like so:
public function onHandleIntent(){
makeRequest("http://somehthing.com", new Handler(){
doStuff();
});
}
onHandleIntent() finishes immediately, before the HTTP request returns. The request does return, but the ServiceIntent thread has already been destroyed and doStuff() doesn't ever run.
What is the best way to handle a callback Handler structure like this with a ServiceIntent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,你没有。
IntentService
旨在对同步工作块进行排队,在另一个线程中完成它们,然后完成。您必须创建自己的服务。您可以查看IntentService
的源代码 并从那里开始。最重要的是,您需要在回调完成后调用stopSelf
,而不是在onHandleIntent
之后调用。Unfortunately, you don't.
IntentService
is meant to queue off synchronous blocks of work, complete them in another thread, then finish. You'll have to create your own Service. You can take a look at the source code forIntentService
and start from there. Most importantly, you'll want to callstopSelf
after the callback is completed instead of afteronHandleIntent
.