Bara
Bara

Reputation: 1113

Android - Having a service run every day at 4AM

I would like to know the best practices for running a Service every day at 4AM.

The way I think I should be doing it is to create a new repeating alarm using AlarmManager and having it run the service at 4AM. Problem is, I'm not sure where to put the code to set the alarm.

Do I do it in my main activity as one of the first tasks in the OnCreate method? Do I do some funky stuff with BroadcastReceivers and intents? What happens when a user updates my app? What happens when a user restarts?

Any help with these questions would be much appreciated :) Sample code would be helpful as well!

Bara

Upvotes: 4

Views: 4937

Answers (1)

Fedor
Fedor

Reputation: 43412

You can schedule your alarm each time phone boots and each time your application starts. To listen to phone boot event you can use BroadcastReceiver.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
.
.
.
<receiver android:name=".BootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

For a complete sample you can take a look at Photostream application http://code.google.com/p/apps-for-android. It uses exactly the same approach.

Upvotes: 4

Related Questions