开发者

Android: Best way to fetch data from server (Widget + application)

开发者 https://www.devze.com 2023-03-06 00:36 出处:网络
I\'m developing an Android application where I need to fetch data (news items) from a server. I know how to do this, using threads and/or AsyncTasks, etc, but since I need the data in a widget also, a

I'm developing an Android application where I need to fetch data (news items) from a server. I know how to do this, using threads and/or AsyncTasks, etc, but since I need the data in a widget also, and because I would like to know what way is preferred in general, I thought I'd ask you guys.

I thought of a few specific implementations, namely;

1) Basically create a class which uses Threads to fetch the data, which I access 开发者_如何学Cfrom both my normal Activities and the Widget. Maybe cache the information for later use.

2) Using a Service, which I can ask for data from both my widget and application. This Service doesn't need to be running all the time, but can be started when I need the data and stops when it has fetched and returned the data. This Service can be started periodically to update the data for the Widget, or something like that.

There are probably many ways to solve this, so I'd love to hear what you think is a good approach for this problem.

Thanks in advance, Erik


You can use a service to fetch the data from the server and then save it in the database. You service can send a broadcast which your app/widget can register to listen to and refresh itself when there is new information available.

Since the service does not need to be running all the time, you can use an IntentService.

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

If you are updating at regular intervals, then your after each update, your service can schedule itself to be run again by the android system using the AlarmManager.

The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.


You might want to start a service when the widget updates itself (updatePeriodMillis) and use it to fetch the data store it in a sqldatabase as well as refresh the widget.

This way the data is cached and you can access it from your application without having to over complicate things.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号