WakefulBroadcastReceiver is deprecated

Yeahia2508 picture Yeahia2508 · Nov 10, 2017 · Viewed 19.4k times · Source

For creating a receiver I'm extended WakefulBroadcastReceiver in my old project. But now it's deprecated. Instead of WakefulBroadcastReceiver which Receiver I should use now and how to convert below code with new method?

Here is my code:

 public class TaskFinishReceiver extends WakefulBroadcastReceiver {
    private PowerManager mPowerManager;
    private PowerManager.WakeLock mWakeLock;
    @Override
    public void onReceive(Context context, Intent intent) {
        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        turnOnScreen();
        Intent wakeIntent = new Intent();

        wakeIntent.setClassName("com.packagename", "com.packagename.activity.TaskFinished");
        wakeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(wakeIntent);
    }


    public void turnOnScreen(){
        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
        mWakeLock.acquire();
    }
}

Answer

Bolling picture Bolling · Jun 27, 2018

You can rewrite your code like this:

    public class TaskFinishReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //do your stuff in the JobIntentService class
            MyJobIntentService.enqueueWork(context, intent);
        }
    }

This will work since, according to documentation, the new JobIntentService class will handle both wake locks and backward compatibility:

You do not need to use WakefulBroadcastReceiver when using this class. When running on Android O, the JobScheduler will take care of wake locks for you (holding a wake lock from the time you enqueue work until the job has been dispatched and while it is running). When running on previous versions of the platform, this wake lock handling is emulated in the class here by directly calling the PowerManager; this means the application must request the WAKE_LOCK permission.