6
votes

I have a broadcastreceiver called by an Alarm (scheduled with AlarmManager). In this receiver I'm only querying a register from the database, and launching a notification. I readed that a wake lock is needed when a service or an activity is started from a broadcast receiver, but, do I need a wake lock if I only want to show a notificacion (in the notification panel)?

2

2 Answers

17
votes

In this receiver I'm only querying a register from the database, and launching a notification.

Do not do database I/O on the main application thread.

I readed that a wake lock is needed when a service or an activity is started from a broadcast receiver, but, do I need a wake lock if I only want to show a notificacion (in the notification panel)?

In general, no, you would not need a WakeLock from a BroadcastReceiver, even one that is invoked via a _WAKEUP alarm. AlarmManager guarantees in this case that it will keep the device awake using its own WakeLock.

However, again, in this case, you really should not be doing database I/O on the main application thread, and onReceive() is called on the main application thread. The proper pattern here is that you move your "querying a register from the database, and launching a notification" to an IntentService, started by your BroadcastReceiver, so that the work is done on a background thread. This will require a WakeLock, as you are now doing work outside of onReceive(). I have a WakefulIntentService that manages the WakeLock for you, if you wish to use it.

-1
votes

Yes, it is necessary. I remember that in the Kernel level, the CPU will be kept running for about 5 seconds. So if you cannot finishing send your notification within 5 seconds, you have to grasp a wake lock. And release it after you finished your work.