问题
I recently tried to use the WorkManager
's PeriodicWorkRequest
s as a surefire way of getting user location updates periodically in the background. The library met my requirements and this particular detail got my attention:
Guarantees task execution, even if the app or device restarts
Having implemented and tested it, I tried rebooting my device and noticed the Log message and App Notification never showed up.
Naturally, I did some research and stumbled upon this: PeriodicWorkRequest not working after device reboot in android oreo
So I tried using the BOOT_COMPLETED
broadcast receiver to trigger the WorkRequest on device reboot but it didn't work. I checked numerous BOOT_COMPLETED
receivers questions on SO but none worked, other than this here: Broadcast Receiver Not Working After Device Reboot in Android but that involved making the user select your app as an AccessibilityService which is a hinderance to the UX in my opinion.
After some research I found out that the WorkManager uses the BOOT_COMPLETED BroadcastReceiver under the hood. I have been testing on Android Nougat and Oreo devices so far, so I tested the BroadcastReceiver on a Samsung running API 16, and also on an HTC running API 22. The Receiver worked and I removed them and also tested the WorkRequests on reboot; they worked too!
Here's how I implemented my PeriodicWorkRequest
PeriodicWorkRequest request =
new PeriodicWorkRequest.Builder(LocationListenerWorker.class,
12, HOURS)
.build();
mWorkManager.enqueueUniquePeriodicWork(Constants.LOCATION_TASK_ID,
ExistingPeriodicWorkPolicy.REPLACE, request);
Would appreciate any help on how to ensure the Requests also get called on device reboot on devices running API 24+
回答1:
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);
}
}
}
来源:https://stackoverflow.com/questions/55305619/how-to-ensure-periodicworkrequests-are-called-on-device-reboot-on-android-n-and