In my Android app, I have some data that needs to be synced daily but also needs to be updated every hour when a user is inside the app.
I have already implemented a service that gets called from an alarm for the daily update. Im having a problem with developing a strategy to do the hourly sync. I could use an hourly alarm too and fire the same intent, but since your app can be killed at any time, there would be no way to cancel it (and since they use the same Intent, doing a cancel would cancel ALL alarms including my daily sync, so that’s probably not good).
The other option is to use a Timer that’s set when inside the app, and have that fire my Intent when inside the app. Im assuming all Timers get cancelled when an app is killed right? But my app consists of several activities and I want the timer to work across all activities, how do I do that? I dont want to duplicate code – we’re already using a subclass for Activity and ListActivity.
The solution seems easy: drop the second requirement. Few apps are used continuously for hours on end, since people tend to use their Android phones for other things (e.g., phones), so your update-hourly-if-used-all-the-time code will probably never run.
FWIW, your app will not be killed while it is on-screen. And, while it is not on-screen, you don’t want the updates going hourly.
Apps generally are not “killed”. We expect you to clean up after yourself when your activities are called with
onDestroy(). If you set up theTimerwith a daemon thread, you will need to terminate that thread.Bind to your service from each of your activities. If it is started by your alarm
Intent, have it do normal update processing. If it is started due to a binding request, just have it make sure its hourlyTimeris running. When it is called withonDestroy()(e.g., after all activities have unbound), have it stop theTimer.