Android:Appwidget 中的网络操作
我正在为我的应用程序开发一个 Android AppWidget。为了更新我的应用程序小部件,我需要从网络下载数据。但是当我尝试在 onUpdate 方法中执行此操作时,我的 appWidget 被 Android 系统杀死。我了解到耗时的操作无法在接收器中完成,因此我从 onUpdate 方法启动了一个服务,并从中启动了一个线程。但问题仍然存在。 谁能告诉我如何在 Appwidget 中进行网络操作?
I'm developing a Android AppWidget for my application. For updating my appwidget I need to download data from network. But when I try to do that in onUpdate method, my appWidget is killed by Android system. I learnt that time consuming operations can't be done in receivers so I launched a service from onUpdate method and launched a thread from that. But still the problem persists.
Can anyone please let me know how to do network operations in Appwidget?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将下载工作委托给一个服务,可能是一个
IntentService
,也可能是一个WakefulIntentService
取决于设备在工作过程中是否存在进入睡眠状态的风险。您的
AppWidgetProvider
只需在您的IntentService
上调用startService()
即可。您的
IntentService
onHandleIntent()
方法将完成您目前在onUpdate()
中所做的工作,获取自己的AppWidgetManager
通过静态getInstance()
方法。但是,由于onHandleIntent()
是在后台线程上执行的,因此您可以根据需要花费尽可能多的时间。一旦完成所有未完成的工作请求,IntentService
也会自动关闭。Delegate the download work to a service, probably an
IntentService
, possibly aWakefulIntentService
depending on whether there is a risk that the device might fall asleep during the work itself.Your
AppWidgetProvider
would just callstartService()
on yourIntentService
.Your
IntentService's
onHandleIntent()
method would do the work you presently have inonUpdate()
, getting its ownAppWidgetManager
via the staticgetInstance()
method. But, sinceonHandleIntent()
is executed on a background thread, you can take as much time as you need. TheIntentService
will also automatically shut down once it is done with all outstanding work requests.