Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WorkManager not repeating the PeriodicWorkRequest

I am creating an android application to run my code in background. I'm well aware of the restriction introduced by the Android Oreo for background services and that's why I'm using WorkManager API to schedule the task for the execution. I'm testing my code on Mi Max device with Android API 24 (Nougat) and also enable the auto start manually so that MIUI allows the app to run in background but the problem is, the WorkManager fires for the first time the application starts but after that, it doesn't work. Below is my code I'm using for the periodic work request and work itself.

PeriodicWorkRequest call:

PeriodicWorkRequest work = new PeriodicWorkRequest.Builder(ClassExtendingWorker.class, 15, TimeUnit.MINUTES)
            .setConstraints(Constraints.NONE)
            .build();
WorkManager.getInstance().enqueue(work);

ClassExtendingWorker:

public Result doWork() {
    /*--- SHOWING NOTIFICATION AS AN EXAMPLE TASK TO BE EXECUTED ---*/
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "")
            .setSmallIcon(R.drawable.common_google_signin_btn_icon_light)
            .setContentTitle("TestApp")
            .setContentText("Code executed")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
    notificationManager.notify(1234, mBuilder.build());

    return Result.SUCCESS;
}
like image 759
Madhusudan Sharma Avatar asked Jun 23 '18 09:06

Madhusudan Sharma


2 Answers

according to the documentation:

 /**
 * The minimum interval duration for {@link PeriodicWorkRequest} (in milliseconds).
 */
public static final long MIN_PERIODIC_INTERVAL_MILLIS = 15 * 60 * 1000L; // 15 minutes.
/**
 * The minimum flex duration for {@link PeriodicWorkRequest} (in milliseconds).
 */
public static final long MIN_PERIODIC_FLEX_MILLIS = 5 * 60 * 1000L; // 5 minutes.

if you are setting this two value less than min specified, then you have to wait approx 20 min to see the log/output

like image 198
Abhilash Das Avatar answered Nov 26 '22 12:11

Abhilash Das


If you use PeriodicWorkRequest with interval less than 15 min, you should return Result.retry(), not success or failure.

like image 20
Sylvester Yao Avatar answered Nov 26 '22 11:11

Sylvester Yao