Android: the best way to get data from the server (Widget + application)

I am developing an Android application where I need to receive data (news) from a server. I know how to do this using streams and / or AsyncTasks, etc., but since I need data in widgets, and because I would like to know which path is preferable in general, I thought I would ask you guys.

I thought of a few specific implementations, namely:

1) In principle, create a class that uses Threads to retrieve data from which I access both from my usual actions and from the widget. Perhaps cache information for future reference.

2) Using a service that I can request from my widget and application. This service does not have to work all the time, but it can be started when I need data, and it stops when it retrieves and returns data. This service can be launched periodically to update data for the widget or something like that.

There are probably many ways to solve this problem, so I would like to hear what you think is a good approach to this problem.

Thanks in advance, Erik

+7
source share
2 answers

You can use the service to retrieve data from the server, and then save it in the database. You can send a broadcast that your application / widget can register to listen and update when there is new information.

Since the service does not need to work all the time, you can use IntentService .

IntentService is the base class for Services that process asynchronous requests (expressed as intentions) for demand. Clients send requests through startService (Intent); the service starts as needed, processes each intention, in turn, using the workflow and stops when it starts outside of work.

If you update at regular intervals, then after each update, your service can plan to start again using the Android system using AlarmManager .

The alarm manager is designed for cases when you want to have the application code executed at a certain time, even if your application is not currently running.

+2
source

You might want to start the service when the widget is updated (updatePeriodMillis) and use it to retrieve data in the sqldatabase repository, as well as to update the widget.

Thus, the data is cached, and you can access it from your application without overloading it.

0
source

All Articles