Search code examples
androidasynchronoustimertaskalarms

Best strategy to implement this behavior in Android app?


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.


Solution

  • 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.

    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.

    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

    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.

    Im assuming all Timers get cancelled when an app is killed right?

    Apps generally are not "killed". We expect you to clean up after yourself when your activities are called with onDestroy(). If you set up the Timer with a daemon thread, you will need to terminate that thread.

    But my app consists of several activities and I want the timer to work across all activities, how do I do that?

    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 hourly Timer is running. When it is called with onDestroy() (e.g., after all activities have unbound), have it stop the Timer.