Search code examples
androidservicebroadcastreceiveralarm

Should an alarm be built with Service or BroadcastReceiver?


I want to build an alarm application. I've seen some examples and some of them use Service and some use BroadcasterReceiver. The user will set the alarm and then when it goes off they'll have to do certain things like solve a mathematical equation or scan NFC tag before it turns off. Which one should I use?


Solution

  • If you are using AlarmManager with a _WAKEUP alarm, you must have the PendingIntent route to a BroadcastReceiver. The only thing Android guarantees with a _WAKEUP alarm is if you use a BroadcastReceiver, Android will keep the device awake long enough for onReceive() to complete. Anything else, all bets are off.

    It the work you want to do would take more than a couple of milliseconds, have the BroadcastReceiver turn around and pass control to a service, which can do its work on a background thread. You may wish to use my WakefulIntentService for that; if not, you will need to manage your own WakeLock to ensure that the device stays awake until the service can complete its work.