Serviceの使い方
Serviceとは、処理をバックグラウンドで実行するための仕組みで、バインドを使用しない方法と、バインドを使用する方法の2つがあります。(インデントずれているの、直す余裕なくてすみません)
バインドを使用しないサービスの実行に必要な構成要素
サービス用のclassを定義する
public class xxxService extends Service {
public IBinder onBind(Intent arg0) { /* なんか知らないけどとりあえず定義が必要らしい */
return null;
}
public void onCreate() {
super.onCreate();
:
}
public void onStart() {
super.onStart();
:
}
public void onDestroy() {
super.onDestroy();
:
}
}
アクティビティの中にリスナーを置いて、その中でインテントを生成し、startServiceで実行する
例.ボタンクリックリスナー
class xxxListener implements OnClickListener {
public void onClick(View v){
Intent intent = new Intent(アクティビティクラス名.this, xxxService.class);
startService(intent);
}
}
バインドを使用したサービスの実行に必要な構成要素
AIDL定義ファイルを作成する(srcの下)
BindActivityAIDL.aidl
interface BindActivityAIDL {
void setDebugMessage(String msg); //このメソッド名は任意です
}
BindServiceAIDL.aidl
import com.hoge.android.sample.BindActivityAIDL; //例です。パス名は個々の実装の仕方で変わります
interface BindServiceAIDL {
void registerCallback(BindActivityAIDL callback);
void unregisterCallback(BindActivityAIDL callback);
}
サービス用のclassを定義する
public class xxxService extends Service {
// callback管理リスト
private final RemoteCallbackList<アクティビティ側のinterfaceの名前> callbackList
= new RemoteCallbackList<アクティビティ側のinterfaceの名前>();
public void onCreate() {}
public IBinder onBind(Intent intent){}// バインドイベントハンドラ
public boolean onUnbind(Intent intent) {} // アンバインドイベントハンドラ
private サービス側のinterface名.Stub serviceCallbackIf = new サービス側のinterface名.Stub() {}
}