IntentServiceでstopService()が使えないということを備忘録として残しておく。
作りたかったもの
ActivityからIntentServiceを通してサーバに通信し、opPause()が呼ばれたら通信キャンセルするプログラム。
ActivityのonPause()は以下のように実装していた。
@Override
protected void onPause() {
super.onPause();
stopService(intent);
}
しかし、onPause()を呼んでも通信が最後まで行われた。
ネット上のサンプル
上記の実装をしたのはネット上に
IntentServiceはstopService()かstopSelf()を明示的に呼ばなくてよい。
終了させたいときは呼んでもよい。
と書いてあったからである。(どのサイトだったかは忘れた…)
しかし、公式リファレンスには「呼ばなくてよい」ではなく「呼ぶべきじゃない」と書いてあった…
This method is invoked on the worker thread with a request to process. Only one Intent is processed at a time, but the processing happens on a worker thread that runs independently from other application logic. So, if this code takes a long time, it will hold up other requests to the same IntentService, but it will not hold up anything else. When all requests have been handled, the IntentService stops itself, so you should not call stopSelf.
This method may take several seconds to complete, so it should only be called from a worker thread.
(ただしstopSelf()は呼ぶべきじゃないとだけ書いてあり、stopService()についてはわからないが、おそらく同様じゃないかなぁと思っている)
代替案
onPause()内でboolean型変数をtrueにして、それがtrueの時は異なる処理をすればよい。
注意していただきたいのは、サービスを途中停止できないことである。IntentServiceはonHandleIntent()が呼ばれると、渡されたタスクを全て処理するまで終了しないので、キャンセルする手段が見つからない。(あるかもしれないが、私の知るところではない)
もしどうしてもキャンセルしたかったら、
AsyncTaskを使う、Serviceクラス(フォアグラウンドなので通信はできない)を使うなどが考えられる。
感想
今回は「ネットのサンプルを信じすぎた」ので、「公式を読む」ということも心掛けたい。
というかこっちのほうが重要である。