2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WorkManagerを停止させる

Last updated at Posted at 2019-09-10

既にプロダクトで動いている WorkManager を停止させたいとき。

単純にWorkerを発火させるところをコメントアウトすれば解決! にはなりません:worried:
この場合、新規ユーザーは問題ありませんが、既存ユーザーの場合が問題です。

既存ユーザーの場合、既に Worker の Request が登録されていると、 Worker は動いてしまうので停止処理を入れてあげる 必要があります。

Worker に登録されている かつ 登録されている Work のステータスがキューにあるか実行中の場合にその Work を停止させる処理の例です。


final ListenableFuture<List<WorkInfo>> listenableFuture =  WorkManager.getInstance(context).getWorkInfosForUniqueWork(MyWorker.UNIQUE_WORK_NAME);
try {
    final List<WorkInfo> workList = list.get();
    if (workList != null && workList.get(0) != null) {
        final WorkInfo.State status = workList.get(0).getState();
        if (status == WorkInfo.State.ENQUEUED || status == WorkInfo.State.RUNNING) {
            WorkManager.getInstance(context).cancelUniqueWork(MyWorker.UNIQUE_WORK_NAME);
        }
    }
} catch (ExecutionException | InterruptedException e) {
    e.printStackTrace();
}

上記のコードの流れは以下の通りです。

  • getWorkInfosForUniqueWorkでWorkerのnameを指定して、ListenableFuture>型のlistenableFutureを取得
  • list.get()でWorkInfoのリスト、workListを取得
  • このworkListがnullでなければ、それはつまりMyWorkerのWorkが現在存在していることを意味する
  • workList.get(0).getState()は先頭のWorkのステータス、statusを取得
    statusが ENQUEUED または RUNNING の場合は、cancelUniqueWorkメソッドでそのWorkをキャンセルする
2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?