Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to download data in the background at specified times

I'm sorry in advance for not having any code to post up, mainly because I can't for the life of me figure out how I need to do what I need to do.

Basically, at specified intervals during the day (ex. 5 P.M), I want my app to download some data from my server and store it on the device. This is to both reduce the load on my server from having data being downloaded every time the app is run, and to reduce the loading times for the user so that when they go to use the app, the latest data is already sitting on their device.

I have absolutely no clue how to do this. I know how to download data just fine, but now how to download in the background like I'm planning. Is it even possible?

I'm not asking for anyone to do it for me, but could someone please point me in the right direction.

like image 620
Kyle Hughes Avatar asked Jul 13 '10 02:07

Kyle Hughes


2 Answers

Use the AlarmManager

This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

Use it to start a Service

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

The API Demos includes an Alarm Service example (in the "App" section), which:

Demonstrates how you can schedule an alarm that causes a service to be started. This is useful when you want to schedule alarms that initiate long-running operations, such as retrieving recent e-mails.

In particular, see AlarmService.java for an example of using AlarmManager to schedule your Service to be woken later, and see AlarmService_Service.java for an example of how to respond to that alarm. The API Demo's AndroidManifest.xml contains the related service and activity definitions:

    <service android:name=".app.AlarmService_Service" android:process=":remote" />

    <activity android:name=".app.AlarmService" android:label="@string/activity_alarm_service">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.SAMPLE_CODE" />
        </intent-filter>
    </activity>
like image 113
Stephen Denne Avatar answered Oct 05 '22 18:10

Stephen Denne


Write a Service.

Use the AlarmManager.

like image 22
Loxley Avatar answered Oct 05 '22 19:10

Loxley