views:

287

answers:

1

Hello everyone,

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

+2  A: 

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.

Fedor
So it looks like I create a BroadcastReceiver that simply calls a Service and tells it to schedule a time to start. Sounds simple enough. How about for when my application starts? Should I schedule the service in my first activity or is there a different intent I can call?
Bara
First activity is great
Fedor
One last question: How about when a user updates my app? They won't necessarily start it up or restart their phone, but I believe my service is shutdown at that point. What would I do about that?
Bara
You can't be sure service is always running. System may kill it on low memory. A possible overcome is to schedule larm to run not at 4AM but each hour. This way if service is killed it will be restarted the next hour. Photostream really does something like that so you can take a look.
Fedor
Well, my service will be a bit intensive. I can't have it running every hour or it'll suck the user's battery dry :p However, thanks for all the help. I'll continue looking at the source code in the links you provided me and I think I can figure it out from there. Thanks again!
Bara