LcSalazar
LcSalazar

Reputation: 16841

Does WakefulBroadcastReceiver require an IntentService in order to hold the wake lock?

I'm developing an app that needs to receive GCM notifications (and send info to the server) at any time, so the device should keep awake to receive it, even when screen is turned off for a long period.

I'm using a WakefulBroadcastReceiver, which should ensure the device holds a wake lock to receive the Notifications at any time (as I could understand, if I'm mistaken, please correct me)

But I'm not calling an Intent Service (as instructed in the docs), instead I'm performing the work in the very Broadcast Receiver onReceive method:

public class GCMReceive extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
        /* Do my work */
    }
}

It works fine, except when the device is inactive for a long time, then it stops receiving the notifications. Am I missing something here? Does the WakefulBroadcastReceiver requires the Intent service in order to hold a wake lock correctly?

Upvotes: 3

Views: 2222

Answers (2)

mmlooloo
mmlooloo

Reputation: 18977

so the device should keep awake to receive it

No, your device may be sleeping when it receives the notification.

WakefulBroadcastReceiver, which should ensure the device holds a wake lock to receive the Notifications at any time

No, WakefulBroadcastReceiver is not created for that purpose actually you misunderstand it. Your CPU falls sleep after being idle for a while. when a notification receives, it wakes up and runs onRecieve method of your BroadcastReceiver. Now consider you want to do a lot of work in onRecieve method, because it is running on the main thread you will get ANR error, so people usually creating an intentService and do their works on a worker thread which the service provides by default. Now you are doing a lot of work on a worker thread, so there is a possibility that the CPU goes sleep because you do not create any lock on the CPU, so you have to take a lock and make the CPU keep awake. In order to do that and in order to make it easy for developers android team create WakefulBroadcastReceiver.

then it stops receiving the notifications.

you have made some mistakes, because receiving notifications dose not despond on the state of CPU.(If you define the receiver in your manifest).

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006779

instead I'm performing the work in the very Broadcast Receiver onReceive method

You are welcome to use a regular BroadcastReceiver, then. WakefulBroadcastReceiver is doing you no good. However, unless that work is less than a few milliseconds, you really should have an IntentService do the work.

Does the WakefulBroadcastReceiver requires the Intent service in order to hold a wake lock correctly?

WakefulBroadcastReceiver does not acquire the WakeLock until you call startWakefulService().

Upvotes: 8

Related Questions