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);
Cancelling and stopping work If you no longer need your previously enqueued work to run, you can ask for it to be cancelled. Work can be cancelled by its name , id or by a tag associated with it. workManager. cancelAllWorkByTag("syncTag");
WorkManager is intended for work that is required to run reliably even if the user navigates off a screen, the app exits, or the device restarts. For example: Sending logs or analytics to backend services. Periodically syncing application data with a server.
To get started using WorkManager, first import the library into your Android project. Once you've added the dependencies and synchronized your Gradle project, the next step is to define some work to run.
You can use enqueueUniquePeriodicWork
instead of enqueue
. Based on the documentation:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With