Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the WorkStatus create by WorkManager in Android?

I create some OneTimeWorkRequest When I use the android-arch work WorkManager.

I can watch WorkStatus by observer like this

final WorkManager workManager = WorkManager.getInstance();
final LiveData<List<WorkStatus>> workStatus =
    workManager.getStatusesByTag(DailyWorker.DAILY_WORK);
observer = new Observer<List<WorkStatus>>() {
  @Override public void onChanged(@Nullable List<WorkStatus> workStatuses) {
    Log.d("WorkManager", "onChanged  = workStatuses = " + workStatuses);
    if (workStatuses == null || workStatuses.size() == 0) {
      //DailyWorker.createNewPeriodWork();
    } else {
      Log.d("WorkManager ", "onChanged  = workStatuses.size() = " + workStatuses.size());
      for (int i = 0; i < workStatuses.size(); i++) {
        Log.d("WorkManager ", "onChanged Work Status Id: " + workStatuses.get(i).getId());
        Log.d("WorkManager ", "onChanged Work Status State: " + workStatuses.get(i).getState());
      }
    }
    workStatus.removeObserver(observer);
  }
};
workStatus.observe(this, observer);

My Android arch version is android.arch.work:work-runtime:1.0.0-alpha02

But there are a lot of WorkStatus in the list,some SUCCEEDED ,some ENQUEUED , some CANCELLED, and the number of the list continue increase. how can I clear the WorkStatus List?

like image 545
Jamin Avatar asked Jun 13 '18 11:06

Jamin


People also ask

How do I cancel WorkManager on Android?

Stop a running Worker You explicitly asked for it to be cancelled (by calling WorkManager. cancelWorkById(UUID) , for example). In the case of unique work, you explicitly enqueued a new WorkRequest with an ExistingWorkPolicy of REPLACE . The old WorkRequest is immediately considered cancelled.

How do I stop periodic requests on Android?

You can also cancel WorkRequests by tag using WorkManager. cancelAllWorkByTag(String). Note that this method cancels all work with this tag. Additionally, you can cancel all work with a unique name using WorkManager.

What is the use of WorkManager in Android?

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.

Is WorkManager deprecated?

This method is deprecated. Gets a LiveData of the last time all work was cancelled. Gets a ListenableFuture of the WorkInfo for a given work id.


1 Answers

You can call the method pruneWork() on your WorkManager to clear the List<WorkStatus>.

myWorkManager.pruneWork();

Hope it helps!

like image 144
CodeNovice Avatar answered Oct 01 '22 17:10

CodeNovice