Pratik Butani
Pratik Butani

Reputation: 62401

WorkManager executing every time when I install (run) app

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.

MyWorker.java

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();
    }
}

Starting worker when login successfully.

PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, 30, TimeUnit.MINUTES)
            .addTag("Location")
            .build();

WorkManager.getInstance().enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.REPLACE, periodicWork);

Problem:

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

Answers (4)

Jonah Mutua
Jonah Mutua

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

Kaaveh Mohamedi
Kaaveh Mohamedi

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 with uniqueWorkName, it will be cancelled and the new work will run. KEEP will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.

Upvotes: 1

Jude Osbert K
Jude Osbert K

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

pfmaggi
pfmaggi

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

Related Questions