Search code examples
androidservicebroadcastreceiveralarmmanager

BroadcastReceiver or Service?


I have an AlarmManager that triggers an alarm every X minutes.

When the alarm is trigger I'm doing a few operations like reading a small file and updating the SharedPreferences.

What is recommended to use for these operations in this case?

A service seems fitting but since these are relatively short operations, maybe a BroadcastReceiver is better (lighter?)?

It seems that both BroadcastReceiver and a Service are running on the same process and on the UI thread and the only difference is how and when Android is killing them. Is that correct?

As far as I understand the AlarmManger can either call a Receiver or a Service (or an Activity but that's irrelevant now). My alarm runs always, even when my app is not running. So either way (a service or a broadcastreceiver) will start my process if it's my app isn't running. The alarm can go off every even 10 seconds, it depends on the user. So in that case, IntentService will have to start a thread every 10 seconds. Isn't that "harsh" on the system? Thanks.


Solution

  • If you are already using an AlarmManager, then use a BroadcastReceiver in whatever Activity (or Fragment) has the code to perform the operations you mention. Remember that either will run on the UI Thread, so use an AsyncTask or Thread.

    You don't need a service running because your alarm will be triggered by the AlarmManager. No need to spawn a new process (Service) for that.

    You could approach the problem from another point of view (if you use a Service) by not using AlarmManager and post a Runnable every X minutes, but the first approach should be ok.

    UPDATE:

    Perhaps you misunderstood me. A service can run in a different process (although it doesn't do it by default), but it's different from a BroadcastReceiver. If you are using an AlarmManager, there's no need to have a Service running.

    The difference between Service and BroadcastReceiver is usually a source of confusion among new Android devs.

    Without knowing the nature of the work you need to perform every X minutes, it's hard to tell what the best scenario is.

    As long as you understand the consequences of running a Service (in its different modes) and/or how not to block the UI thread, then yes, using a Service is usually good, even an IntentService can help you.

    Perhaps you want to couple your AlarmManager with an IntentService, but beware that this doesn't prevent the device from going to sleep, you might as well use a WakefulIntentService that will keep a wakelock for you.