IntentServiceも非同期処理を行うクラスだが、こちらはServiceの派生クラスで、主に画面遷移に関係なくバックグラウンドで時間のかかる処理を任せる場合に使う・・・。
IntentService | Android Developers
プロジェクトを作成したら、
IntentServiceの派生クラス、CustomIntentServiceを追加・・・。
nameを引数とするコンストラクタが必須なのだが、実際に今回呼ばれるのは引数なしのコンストラクタ・・・。
その場合、superでクラス名文字列を渡しておく・・・。
onHandleIntentが非同期処理本体・・・。
10秒経ったら、intent.getIntExtraで渡された引数を取得できるので、"CustomIntentService finish!"とそれをログに出力・・・。
MainActivityは、
Button1のonClick時に、int型paramに10をセット・・・。
CustomIntentServiceを起動するintentを作成・・・。
intent.putExtraでparamをセット・・・。
あとは"startService"とparamの値をLog.dで出力したら、startServiceでintentの指すサービスを起動・・・。
Button1を押したら、
というログが出て10秒後に、
というログが出る・・・。
paramの値10もちゃんと渡されている・・・。
サービスに非同期処理を任せているので、アクティビティを閉じても終わるまで処理し続ける・・・。
Sample/android/IntentService/IntentService/src/IntentService at master · bg1bgst333/Sample · GitHub