I recently tried to use the WorkManager
\'s PeriodicWorkRequest
s as a surefire way of getting user location updates periodically in the background.
Let Say you have defined a RebootWorker class that extends Worker and do some particular job after device get rebooted. 1st Approach :
public class RebootWorker extends Worker {
...............................
}
In that case defined this worker inside manifest
<service
android:name=".RebootWorker"
android:process=":worker"/>
This will help to get Workmanger run your worker service after device reboot. Because due to device reboot your app is cleared from task manager.
2nd Approach : You can also use BroadcastReceiver to listen Boot completed action
public class MyReceiver extends BroadcastReceiver {
WorkManager mWorkManager;
PeriodicWorkRequest rebootRequest;
@Override
public void onReceive(Context context, Intent intent) {
Log.i(MainActivity.TAG, "intent.getAction(): "+intent.getAction());
//Reboot worker
mWorkManager = WorkManager.getInstance(context);
rebootRequest = new PeriodicWorkRequest.Builder(RebootWorker.class,
MainActivity.REPEAT_INTERVAL, MainActivity.TIME).build();
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
//do your work and enqueue it
mWorkManager.enqueue(rebootRequest);
}
}
}