问题
I have requirement of pushing in app notification to user based on following logic.
- Type A notification will be shown after every 24 hours.
- Type B notification will be shown after every 7 days.
- Type C notification will be shown after every 15 days.
I have used PeriodicWorkRequest
work manager as follows, its working fine until device is restart.
Once device is restart my work is not getting trigger.
build.gradle ---
implementation 'android.arch.work:work-runtime:1.0.0-alpha04'
Java code
PeriodicWorkRequest showNotification =
new PeriodicWorkRequest.Builder(ShowNotificationWorkManager.class, interval,
TimeUnit.HOURS)
.addTag(notificationType)
.setInputData(myData)
.build();
getWorkManger().enqueue(showNotification);
回答1:
Restart your PeriodicWorkRequest in a BroadcastReceiver that is triggered when the device has finished booting up. with intent-filters like so.
<receiver
android:name=".warrantyregistration.boot.BootReceiver"
android:enabled="@bool/configuration_for_receiver_service">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
this answer states how OneTimeWorkRequest behaves when device is restarted.
回答2:
Please add the following permission in your android manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
回答3:
Periodic work request can scheduled once when app is started first time on the device. We can use shared preference to identify whether the app is started first time or not. Moreover, in order to repeat the work after boot, we can start the work in a BroadcastReceiver which will be triggered after rebooting device.
回答4:
Sadly WorkManager doesn't really works after device is rebooted. But good news is that you can make it work in another way.
Simply define a BroadcastReceiver and schedule your WorKManager in onReceive(-) method.
public class WorkManagerStartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Constraints constraints = new Constraints.Builder()
.setRequiresCharging(false)
.build();
PeriodicWorkRequest saveRequest =
new PeriodicWorkRequest.Builder(ToastWorker.class, 15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build();
WorkManager.getInstance(context)
.enqueue(saveRequest);
} }
Now define your BroadcastReceiver in manifest.xml file
<application
----
>
<activity android:name=".MainActivity"/>
<receiver android:name=".WorkManagerStartReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
Hey don't forget to add boot permission in your manifest file android.permission.RECEIVE_BOOT_COMPLETED
来源:https://stackoverflow.com/questions/51439450/periodicworkrequest-not-working-after-device-reboot-in-android-oreo