WakefulBroadcastReceiver in support library vs cwac-wakeful by commonsware
I am using commonsware WakefulIntentService
to do wakefulness. Are there any advantages over using the commonsware library instead WakefulBroadcastReceiver
of the support library?
This is my code using suport library
import android.support.v4.content.WakefulBroadcastReceiver;
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);
}
}
public class SimpleWakefulService extends IntentService {
public SimpleWakefulService() {
super("SimpleWakefulService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
}
This is documentation.
- What are the differences between them?
- Where should I use the commonsware library instead of the suport library?
source to share
They are almost the same.
The support library WakefulBroadcastReceiver
does a partial tracking lock, puts the lock id as an optional one in Intent
which you must provide IntentService
where you should call completeWakefulIntent ()
when you are done processing. So the acquisition and release happens in different places, which is a bit of a code smell.
CommonsWare WakefulIntentService
collects and releases partial trail locks.
You can use regular BroadcastReceiver
in combination with WakefulIntentService
if you agree that the purchase and release should be done in the same place.
If you don't mind that much and think it's more important to use a known library so that new developers (or you over the course of a year) don't have to (re) learn something new, then use the support library.
Update
Also this: in the documentation for WakefulBroadcastReceiver
it, it warns about the possibility of interruption and loss of tracking lock. You will need to purchase your own tracking lock IntentService
to protect against this. With CommonsWare, you can simply rely on it to re-commit the lock.
source to share