3

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 :)

Raj Singh
  • 95
  • 6
  • I have faced this issue is latest WorkManager library "androidx.work:work-runtime:2.4.0" – Raj Singh Oct 07 '20 at 04:40
  • Where are you testing? on a Real device or Emulator? If you are testing on a Real device, who's the manufacturer? Because some devices (ex: MIUI) kill the android background processes when the app is killed or removed from the recent stack. – Soumik Bhattacharjee Oct 07 '20 at 05:58
  • All testing is on emulator... and regarding Chinese manufacturer i know they have this behaviour.. but this observation are on stock android. – Raj Singh Oct 07 '20 at 06:09
  • Sorry for the late response. As I see nothing wrong in your code. One thing you can try. Return `Result.retry()` only when you encounter some exception, other than this try returning `Result.success()` Like this: `try { yourWork() } catch(exception) { return Result.retry() } return Result.success()` – Soumik Bhattacharjee Oct 08 '20 at 04:30
  • Yeah I have also tried that before, and it didn't worked.. So after that I try forcing it by returning "retry" but it didn't worked too, and I end up posting it here. Frankly saying after this I'm not too happy with WorkManager simplicity, as it limits understanding and debugging. – Raj Singh Oct 08 '20 at 05:16
  • @RajSingh have you found any solution to this problem? – radus14 Nov 23 '22 at 13:42

0 Answers0