I am using commonsware WakefulIntentService
for doing wakeful work.
Is there any advantage over using the commonsware library instead of WakefulBroadcastReceiver
from support library?
This is my code using the 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 the documentation.
They are almost the same.
The support library's WakefulBroadcastReceiver
takes a partial wake lock, puts the lock ID as an extra in the Intent
that you are supposed to give to an IntentService
where you must call completeWakefulIntent ()
when you're done processing. So acquiring and releasing is done in different places which is a bit of a code smell.
CommonsWare's WakefulIntentService
does the acquiring and releasing of the partial wake lock itself.
You could use a regular BroadcastReceiver
in combination with the WakefulIntentService
if you agree that acquiring and releasing should be done in the same place.
If you don't mind that much and think it's more important to use a well known library so new developers (or you in a year's time) don't have to (re)learn something new then use the support library.
update
Also this: in the documentation for WakefulBroadcastReceiver
it warns about the possibility of being interrupted and losing the wake lock. You would need to acquire your own wake lock in the IntentService
to guard against that. With CommonsWare's you can just rely on it to reacquire the lock.