I have requirement of pushing in app notification to user based on following logic.
I have used PeriodicWorkRequest
work manager as follows, it's working fine until the device is restarted.
Once device is restarted, my work is NOT getting triggered.
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);
You called getWorkManger().enqueue(showNotification)
. Instead, you should enqueue periodic work because yours is a Periodic Operation:
workManager = WorkManager.getInstance(this)
workManager.enqueueUniquePeriodicWork(
WORKER_NAME, ExistingPeriodicWorkPolicy.KEEP, workRequest
)
I've tried this code & worked with me on old APIs and new ones: This code which executes the service (workmanager) every 15 min when the device reboots. for AndroidManifest.xml file:
<receiver android:name=".WorkManagerStartReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
And on WorkManagerStartReceiver class:
public class WorkManagerStartReceiver extends BroadcastReceiver {
WorkManager mWorkManager;
@Override
public void onReceive(Context context, Intent intent) {
PeriodicWorkRequest.Builder myWorkBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
PeriodicWorkRequest myWork = myWorkBuilder.build();
mWorkManager = WorkManager.getInstance(context);
mWorkManager.enqueue(myWork);
}
}
While TestWorker.class is the class that extends Worker:
public class TestWorker extends Worker {
public TestWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
//your work that you want to execute here
return null;
}
}
And this snippet (on MainActivity) that opens when the app opens if you want the service to start working when the app opens.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PeriodicWorkRequest.Builder myWorkBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
PeriodicWorkRequest myWork = myWorkBuilder.build();
WorkManager.getInstance(MainActivity.this)
.enqueueUniquePeriodicWork("testworker", ExistingPeriodicWorkPolicy.KEEP, myWork);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With