Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
On Application start I want to start service that will work forever, but when user opens app again it duplicates.
PeriodicWorkRequest.Builder sendDataBuilder = new PeriodicWorkRequest.Builder(SendConnectionMetricsWorker.class, Constants.REPEAT_TIME_INTERVAL_IN_HOURS, Constants.REPEAT_TIME_INTERVAL_UNITS)
.setConstraints(new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build());
PeriodicWorkRequest periodicWorkRequest = sendDataBuilder
.build();
WorkManager.getInstance().enqueue(periodicWorkRequest);
This method allows you to enqueue a uniquely-named
PeriodicWorkRequest, where only one PeriodicWorkRequest of a
particular name can be active at a time. For example, you may only
want one sync operation to be active. If there is one pending, you can
choose to let it run or replace it with your new work. The
uniqueWorkName uniquely identifies this PeriodicWorkRequest.
You can achieve it as follows:
PeriodicWorkRequest.Builder sendDataBuilder = new PeriodicWorkRequest.Builder(SendConnectionMetricsWorker.class, Constants.REPEAT_TIME_INTERVAL_IN_HOURS, Constants.REPEAT_TIME_INTERVAL_UNITS)
.setConstraints(new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build());
PeriodicWorkRequest periodicWorkRequest = sendDataBuilder
.build();
WorkManager.getInstance().enqueueUniquePeriodicWork("Send Data", ExistingPeriodicWorkPolicy.KEEP,periodicWorkRequest);
Note:
ExistingPeriodicWorkPolicy.REPLACE
ensures that if there is pending work labelled with uniqueWorkName, it will be cancelled and the new work will run. ExistingPeriodicWorkPolicy.KEEP
will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.