Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 from 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

like image 577
Erik Avatar asked May 16 '11 12:05

Erik


People also ask

How will you share data between different applications on a device?

Android uses the action ACTION_SEND to send data from one activity to another, even across process boundaries. You need to specify the data and its type. The system automatically identifies the compatible activities that can receive the data and displays them to the user.

Which component is used to share data between two applications?

Content provider is the android component, which has to be used if one application wants to share its data with other application.


1 Answers

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.

like image 59
codinguser Avatar answered Oct 21 '22 11:10

codinguser