从广播接收器启动异步任务
我想知道从广播接收器启动异步任务是否被认为是一种不好的做法?我基本上是在谷歌的C2DM服务器上注册的,然后当我拦截注册的广播接收器时,我想将其发送到我的服务器。
实现这一目标的最佳方法是什么?
I want to know if starting up a asynctask from a broadcast receiver considered a bad practice? I basically registered with the C2DM server of google and then when I intercept the onregistered, broadcast receiver, I want to send it to my server.
what is the best way of accomplishing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这被认为是不好的做法。这是因为,如果您从
BroadcastReceiver
启动AsyncTask
,如果onReceive()
返回并且没有其他活动组件在运行,Android 可能会终止您的进程。正确的方法是从
BroadcastReceiver
启动Service
。这个Service
应该管理AsyncTask
。这样,Android 将了解活动组件,并且 Android 不会过早终止它(除非出现其他关键情况,例如内存不足的情况)。Yes, this is considered bad practice. That's because if you start
AsyncTask
fromBroadcastReceiver
Android may kill your process ifonReceive()
returned and there is no other active components running.The correct way would be to start
Service
fromBroadcastReceiver
. And thisService
should manageAsyncTask
. This way Android will be aware about the active component and Android will not kill it prematurely (unless other critical conditions arise, like not enough memory conditions).从 Honeycomb 开始,您可以调用 goAsync( ),然后您有 10 秒左右的时间异步完成工作。
此处显示了使用示例。
Starting with Honeycomb, you can call goAsync(), and then you have 10 seconds or so to do your work asynchronously .
Example of usage can be shown here.