Reputation: 62401
I have created two Worker through WorkManager. Its settled for every 30 minutes after I logged in successfully.
Once I logged in, Its started successfully and working as expected.
public class MyWorker extends Worker {
private Context mContext;
public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
mContext = context;
}
@NonNull
@Override
public Result doWork() {
Log.d(TAG, "doWork: Done");
return Result.success();
}
}
PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, 30, TimeUnit.MINUTES)
.addTag("Location")
.build();
WorkManager.getInstance().enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.REPLACE, periodicWork);
When I run my app, its executing again. Its happening every time when I install (run) my app.
Is there any solution for this?
Upvotes: 4
Views: 1999
Reputation: 1
Remove the .addTag("Location")
line.
Change the ExistingPeriodicWorkPolicy attribute from REPLACE to KEEP.
Keep the rest of the code as is. This one should work fine for you.
Check out this link to learn more.
Upvotes: 0
Reputation: 1795
I think you must use ExistingPeriodicWorkPolicy.KEEP
instead of ExistingPeriodicWorkPolicy.REPLACE
According to document:
REPLACE
ensures that if there is pending work labelled withuniqueWorkName
, it will be cancelled and the new work will run.KEEP
will run the newPeriodicWorkRequest
only if there is no pending work labelled withuniqueWorkName
.
Upvotes: 1
Reputation: 1048
This will happen if your workermanager is running a periodic task. If you can add a check by a flag in sharedpreference or something to check if the process has already started. Otherwise you will have to uninstall and then run it
Upvotes: 0
Reputation: 6476
If you are using Android Studio to install and run your application, that gets classified as a force stop.
If your app uses PeriodicWork, we need to reschedule all work. So it will run every time the app process is force stopped by Studio.
Upvotes: 0