PeriodicWorkRequest not working after device reboo

2019-06-19 08:03发布

问题:

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" />