WorkManager: Periodic work not working expectedly

1k views Asked by At

Note: I have already checked out multiple similar post and tried all possible general solutions, and also most of the respected posts were almost an year old or more. Now I'm re-raising issue w.r.t to observation and efforts.

Expectation: Firstly, I am looking out to create a periodic service/work that should be running even the application got closed or terminated/cleared for recent. The purpose of this will be to hit any database on interval ---> fetch and trigger a notification to user.

Here is my current code:

MainActivity -> onCreate ->

PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(
            NotificationWorker.class,
            1, 
            TimeUnit.HOURS)
            .setConstraints(
                    new Constraints.Builder()
                            .setRequiredNetworkType(NetworkType.CONNECTED)
                            .build()
            )
            .build();

 WorkManager.getInstance(this)
            .enqueueUniquePeriodicWork("simplified", ExistingPeriodicWorkPolicy.REPLACE, workRequest);

NotificationWorker class ->

public class NotificationWorker extends Worker {
private static final String TAG = "DANTE:NotifyWorker";
private Context mContext;
public NotificationWorker(@NonNull Context context,
                          @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
    mContext = context;
}

@NonNull
@Override
public Result doWork() {
    Log.d(TAG, "doWork: called");
    NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(mContext);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                "My app",
                "My app",
                NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription("My description.");
        mNotificationManager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(mContext, "My app");

    mNotificationBuilder.setContentTitle("Work manager")
            .setContentText(String.valueOf(new Date().getTime()))
            .setSmallIcon(R.drawable.ic_app_notification)
            .setPriority(NotificationCompat.PRIORITY_LOW);
    mNotificationBuilder.setProgress(0, 0, true);
    Notification notification = mNotificationBuilder.build();
    mNotificationManager.notify(121, notification);
    return Result.retry();
}

@Override
public void onStopped() {
    super.onStopped();
    Log.d(TAG, "onStopped: called");
}

Observations:

1. As per my understanding PeriodicWorkRequest work in background and executes doWork in interval in my case 1+ hour. But what I have noticed is as soon as app closes and cleared from recent, I never receive a callback/execution to doWork again even after waiting for hours and a day too.

2. As soon as I open app again after 3+ hours, I observer log stack and found out 3-4 times doWork getting logged "doWork: called" which is quiet surprising because I was expecting these logs to be printed on respected intervals.

3. After app close and cleared for recent, my notification also removed from the notification bar, which I never expected as this is my primary use case for having WorkManager.

4. Just for understanding callbacks I have override onStopped also added log in so to get insight, but it never gets called.

Efforts: After going through earlier similar post I have tried the listed below:

1. Changing ExistingPeriodicWorkPolicy - > KEEP, REPLACE

2. Changing Constraints and accordingly wait for response.

3. Created custom provider MyWorkManagerInitializer, placed in AndroidManifest as provider and then executed exact PeriodicWorkRequest from onCreate and found the exact same behavior afore mentioned. I have tested way from medium post https://medium.com/@programmerr47/custom-work-manager-initialization-efdd2afa6459

4. While working on MyWorkMangerInitializer approach I didn't get any exception related to "Work Manager is disable* except in android version 21(Lollipop) which is kind of strange coz its was working on other higher level versions, but in all the working versions my observation was same.

Actively looking out for clarification and solution regarding all observation. Thanks in advance for ur time :)

0

There are 0 answers