如何清除Android中的WorkManager创建的WorkStatus?

时间:2018-06-13 11:53:10

标签: android-architecture-components android-livedata android-workmanager

我创建了一些OneTimeWorkRequest当我使用android-arch work WorkManager时。

我可以通过像这样的观察者观看WorkStatus

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);

我的Android拱形版本为android.arch.work:work-runtime:1.0.0-alpha02

但是列表中有很多WorkStatus,一些SUCCEEDED,一些ENQUEUED,一些CANCELLED,并且列表的数量会继续增加。 如何清除WorkStatus列表?

2 个答案:

答案 0 :(得分:6)

您可以在WorkManager上调用方法pruneWork()以清除List<WorkStatus>

myWorkManager.pruneWork();

希望有帮助!

答案 1 :(得分:0)

制作工作时可以调用WorkRequest#keepResultsForAtLeast