Why is this Worker being triggered twice on first trigger?

Viewed 159

I'm using a WorkManager with constraint checking for external uri change to do something whenever a new photo is taken using the camera, below is some sample code which reproduces the issue I'm having.

The issue is: When my app is first started and the work is first scheduled, when a photo is taken the log outputs "Test" twice. After this it works as expected with only outputting once per photo taken. The same thing happens if I use ExistingWorkPolicy.KEEP instead of ExistingWorkPolicy.REPLACE

What is causing it to output twice the first time?

MainActivity.java:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        scheduleWork("BackgroundWorker");
    }

    public static void scheduleWork(String tag) {
        OneTimeWorkRequest.Builder taskBuilder = new OneTimeWorkRequest.Builder(BackgroundWorker.class);
        taskBuilder.setConstraints(new Constraints.Builder()
                .addContentUriTrigger(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true)
                .build());
        OneTimeWorkRequest task = taskBuilder.build();
        WorkManager workManager = WorkManager.getInstance();
        workManager.enqueueUniqueWork(tag, ExistingWorkPolicy.REPLACE, task);
    }
}

BackgroundWorker.java:

public class BackgroundWorker extends Worker {
    public BackgroundWorker(Context workerContext, WorkerParameters workerParams) {
        super(workerContext, workerParams);
    }

    @Override
    public Result doWork() {
        Log.d("BackgroundWorker", "Test");
        MainActivity.scheduleWork(getTags().iterator().next());
        return Result.success();
    }
}

Edit: Also a sidenote, it takes around 10 - 15sec for my worker to be informed of the new photo, is there any way to reduce this time taken?

Sad, SO seems dead when it comes to android questions, no answers at all to any questions in the past several hours, I guess nobody knows.

1 Answers

Edit: Also a sidenote, it takes around 10 - 15sec for my worker to be informed of the new photo, is there any way to reduce this time taken?

Try these with low values:

https://developer.android.com/reference/androidx/work/Constraints.Builder#setTriggerContentMaxDelay(java.time.Duration)

https://developer.android.com/reference/androidx/work/Constraints.Builder#setTriggerContentUpdateDelay(long,%20java.util.concurrent.TimeUnit)

Also please note that tag and name are not the same things. You are trying to have a unique work, but then taking tags from the work to post later works. I have not run the code, but have you logged what getTags() is giving you? If it is not BackgroundWorker you do not have a unique work and KEEP and REPLACE flags are useless.

Related