Search code examples
javaandroidandroid-servicealarmmanagerandroid-workmanager

Android WorkManager - not working well after application kill


I created simple workManager and I want that in background worked for-loop 50 times every 1 second, so it will iterate loop every 1 second and show log. First let me introduce my code.

This is WorkManager class.

public class WorkerClass extends Worker {

    private static String TAG = "work_tag";

    public WorkerClass(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        try {
            loop();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    private void loop() throws InterruptedException {
        for (int i = 0; i < 50; i++) {
            Thread.sleep(1000);
            Log.d(TAG, "Working: " + i);
        }
    }
}

And here is my MainActivity.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(WorkerClass.class).build();

        WorkManager.getInstance().enqueue(oneTimeWorkRequest);
    }
}

Please inform me if there's something wrong. So when I'm starting app, it shows log every 1 second like this.

D/work_tag: Working: 1
D/work_tag: Working: 2
D/work_tag: Working: 3
D/work_tag: Working: 4
D/work_tag: Working: 5

All right yes? So when I'm killing app (onDestroy), after 30-35 seconds the loop starts again in background. After that when I'm opening application, the loop starts again, without completing the previous loop.

For example in background loop iterated 25 times of 50 and if I'll open the app, log would be something like this.

D/work_tag: Working: 25
D/work_tag: Working: 0
D/work_tag: Working: 26
D/work_tag: Working: 1
D/work_tag: Working: 27
D/work_tag: Working: 2
D/work_tag: Working: 28
D/work_tag: Working: 3
D/work_tag: Working: 29
D/work_tag: Working: 4

You see? After opening app 2 loops start to iterate asynchronously. So first question is how to avoid this to happen (2 loops asynchronously) and second question is why after destroying the application I have to wait 30-35 seconds for working the loop in background?

I'm testing this in android 6.0

In android 4.4 the background task not scheduling at all.


Solution

  • You are running two different copies of the worker at this point - each time your Activity starts, you are enqueuing a new WorkRequest. If you want to use only one copy, use a unique work request: https://developer.android.com/reference/androidx/work/WorkManager#enqueueUniqueWork(java.lang.String,%20androidx.work.ExistingWorkPolicy,%20androidx.work.OneTimeWorkRequest)