64

Can somebody explain what the exact difference is between BroadcastReceiver and WakefulBroadcastReceiver?

In what situations would we have to use each Receiver class?

Ronald Martin
  • 4,278
  • 3
  • 27
  • 32
user2107111
  • 735
  • 1
  • 6
  • 10
  • read the documentation! it is all about WAKE_LOCKs – Selvin Oct 15 '14 at 10:45
  • may i know the reason for down voting my doubt. – user2107111 Oct 15 '14 at 10:46
  • 4
    Answer(for your question, not downvote) is read.. Read [BroadcastReceiver](http://developer.android.com/reference/android/content/BroadcastReceiver.html), after that.. read [WakefulBroadcastReceiver](https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html), [when do you absolutely need wakefulbroadcast...](http://porcupineprogrammer.blogspot.in/2014/02/when-do-you-absolutely-need.html) would help. Else..this isn't the place for your question, please read: [what topics can i ask about](http://stackoverflow.com/help/on-topic) – Pararth Oct 15 '14 at 10:46
  • 1
    i read it but i am unable to understand , can u pls explain me with simple example – user2107111 Oct 15 '14 at 10:49
  • anyways thanks for the suggestion,but one request pls give me some simple example which can make my doubt clear. – user2107111 Oct 15 '14 at 10:52
  • 1
    okay..then there's more read.. [Managing an Android device's awake state](http://www.101apps.co.za/index.php/articles/managing-an-android-device-s-awake-state.html) and [Android Broadcast Receivers: A Tutorial](http://101apps.co.za/articles/android-broadcast-receivers-a-tutorial.html) , i sincerely don't mean to offend, but reading more(try to code samples, see the difference) will be the only help – Pararth Oct 15 '14 at 10:57
  • 1
    First sentence in the WakefulBroadcastReceiver documentation reads: "Helper for the common pattern of implementing a BroadcastReceiver that receives a device wakeup event and then passes the work off to a Service, while ensuring that the device does not go back to sleep during the transition." That's the difference. – Qw4z1 Oct 15 '14 at 11:04
  • 3
    WakefulBroadcastReceiver is deprecated for Android "O" and above. The replacement is JobScheduler. – albert c braun May 28 '17 at 15:42

1 Answers1

110

There is only one difference between BroadcastReceiver and WakefulBroadcastReceiver.

When you receive the broadcast inside onReceive() method,

Suppose,

BroadcastReceiver :

  • It is not guaranteed that CPU will stay awake if you initiate some long running process. CPU may go immediately back to sleep.

WakefulBroadcastReceiver :

  • It is guaranteed that CPU will stay awake until you fire completeWakefulIntent.

Example:

Here, when you receive broadcast, you are starting a service, as you are using WakefulBroadcastReceiver, it will hold wakelock and won't let the CPU sleep until you finish the work inside service and fire completeWakefulIntent

Code:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

class SimpleWakefulService extends IntentService {
    public SimpleWakefulService() {
        super("SimpleWakefulService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.  This sample just does some slow work,
        // but more complicated implementations could take their own wake
        // lock here before releasing the receiver's.
        //
        // Note that when using this approach you should be aware that if your
        // service gets killed and restarted while in the middle of such work
        // (so the Intent gets re-delivered to perform the work again), it will
        // at that point no longer be holding a wake lock since we are depending
        // on SimpleWakefulReceiver to that for us.  If this is a concern, you can
        // acquire a separate wake lock here.
        for (int i=0; i<5; i++) {
            Log.i("SimpleWakefulReceiver", "Running service " + (i+1)
                    + "/5 @ " + SystemClock.elapsedRealtime());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
        }
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }
}
alex
  • 8,904
  • 6
  • 49
  • 75
Mehul Joisar
  • 15,348
  • 6
  • 48
  • 57
  • Hi. Can you elaborate on what do you mean by "CPU going to sleep" in layman terms and if you can give an example it will be helpful. Thanks. – Kaveesh Kanwal Mar 08 '15 at 17:20
  • 6
    @TheHunter: cellphone runs all the processes in CPU (Central Processing Unit). Computers do have the CPU like Intel i3,i5 etc and cellphones also have the CPU like snapdragon. To save energy, whenever the cellphone becomes ideal, user don't interact, display lights turn off and CPU may go in ideal(sleep) mode instead of processing the things. – Mehul Joisar Mar 09 '15 at 04:51
  • 1
    @MehulJoisar, then shoulnt we acquire a wakelock everytime we start a service? Because in that case also it can go to sleep? Why only in case of BroadcastReceivers? – Diffy May 12 '15 at 13:42
  • 1
    @Diffy: Yes, We should worry about it when we start service from anywhere other than WakefulBroadcastReceiver. You may checkout [WakefulIntentService](https://github.com/commonsguy/cwac-wakeful/blob/master/wakeful/src/com/commonsware/cwac/wakeful/WakefulIntentService.java) – Mehul Joisar May 13 '15 at 04:39
  • 2
    Though the answer above is correct, I'd like to add some inputs as well. The intent service used with wakeful broadcast receiver should be used for short operations only (I may be wrong, in which case I'd want some corrections), because the receiver holds a wake lock until the work completes. Holding wake locks for long periods of time can cause heavy battery drains and should be avoided whenever possible. – gaurav jain Sep 06 '15 at 08:41
  • what if we use `WakefulBroadcastReceiver.completeWakefulIntent(intent);` ? Is there a difference? – Bugs Happen Oct 06 '15 at 06:09
  • @BugsHappen: you should use your own extended instance i.e.: `SimpleWakefulReceiver` because `WakeLock` will be acquired by it and you should release by it at the end. – Mehul Joisar Oct 06 '15 at 06:12
  • @gaurav jain, If you check the WakefulBroadcastReceiver source you can see that the wake lock is acquired for no more than 60 seconds. If you did not finish your processing within this time frame the CPU may go to sleep. – MikeL Jun 20 '16 at 09:20
  • So, is WakefulBroadcastReceiver used for alarm-clock apps, before showing an activity of the alarm (or even showing a notification before the alarm, to allow to cancel it) ? – android developer Oct 26 '16 at 07:01
  • @androiddeveloper: It is used for holding the wakelock basically but yes you can create notification and handle its action to cancel alarm without displaying any activity. – Mehul Joisar Oct 26 '16 at 07:39
  • @MehulJoisar Question is if it's useful for alarm clock apps. I also wonder what other cases it can be useful for. – android developer Oct 26 '16 at 07:45
  • @androiddeveloper: it is useful for handling intents. whether it is implicit or explicit. Even intents which are broadcasted by OS. Ultimately, it can handle intents and provides wakelock. (i.e.: ) 1) create/run/destroy a 30sec process time service on every 4hr. 2) handle system intents like Battry low,etc and run your service for business logic based on it. – Mehul Joisar Oct 27 '16 at 06:46
  • 1) SimpleWakefulService add to AndroidManifest.xml 2) If SimpleWakefulReceiver included SimpleWakefulService, then Service must be public and static. – NeoSvet Apr 06 '17 at 17:10
  • @MehulJoisar What if I want invoke `SimpleWakefulReceiver.completeWakefulIntent(intent);` when the CPU the go to sleep? – Roman Nazarevych May 11 '17 at 10:14
  • 2
    WakefulBroadcastReceiver is deprecated on Android O: https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html – Emerson Dallagnol Jun 07 '17 at 18:34
  • illegal state exception in : startWakefulService(context, service);, knows anyone why ? – Noor Hossain Jan 07 '21 at 17:02