WakefulBroadcastReceiver

This class is deprecated.
As of Android O, background check
restrictions make this class no longer generally useful. (It is generally not safe to
start a service from the receipt of a broadcast, because you don't have any guarantees
that your app is in the foreground at this point and thus allowed to do so.) Instead,
developers should use android.app.job.JobScheduler to schedule a job, and this
does not require that the app hold a wake lock while doing so (the system will take
care of holding a wake lock for the job).

This helper is for an old 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.

This class takes care of creating and managing a partial wake lock
for you; you must request the Manifest.permission.WAKE_LOCK
permission to use it.

Wakelocks held by this class are reported to tools as
"androidx.core:wake:<component-name>".

import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
public 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);
}
}