My current experiments learning the Android platform. I'm currently working on an App called WallSwitch that will automagically switch your wallpaper for you, at a defined interval. I figured I might as well do something the iPhone can't do (for now).

Saturday, April 25, 2009

Registering for TIME_TICK After a Reboot in Android

Creating a service that will receive TIME_TICK, but also start on boot isn't immediately obvious. It took me a bit to figure out the best way to do it, so I figure it's worth sharing.

To start, you can't register your receiver to get TIME_TICK in the android manifest. The registration for TIME_TICK has to happen in code using Intent.registerReceiver. You can, however, define that your receiver has android.permission.RECEIVE_BOOT_COMPLETED and set your receiver to handle it, which will give you some control on boot. Here's the relevant portion of AndroidManifest.xml:

This isn't enough, however, since your receiver can't register itself to listen to TIME_TICK. Intent.registerReceiver registers for the lifetime of the Intent it's called from. If we register it using the intent created for BOOT_COMPLETED, it's dead as soon as it exits the handler. Therefore, we need to start a background service that will keep running. This service then creates a new instance of the receiver and registers that for TIME_TICK.

Nice, but how do you stop the service and the notifications that keep coming every minute without uninstalling the application?Once the service is bound to the registered receiver, I could not stop the service once started because it was bound to the registered receiver even when I called stopService(intent) with a static intent from the same app that started the service.