すべてのアクティビティに対して BaseActivity を作成します。BaseActivity で、次の操作を行います。
public class MyActivity extends Activity implements ServiceConnection {
//you may add @override, it's optional
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyService.class);
bindService(intent, this, 0);
}
//you may add @override, it's optional
protected void onStop() {
super.onStop();
unbindService(this);
}
public void onServiceConnected(ComponentName name, IBinder binder) {};
public void onServiceDisconnected(ComponentName name) {};
/* lots of other stuff ... */
}
BaseActivity は ServiceConnection インターフェイスを実装する必要があります (または、匿名の内部クラスを使用できます) が、これらのメソッドを空のままにしておくことができます。
onBind(Intent)
Service クラスでは、メソッドを実装して IBinder を返す必要があります。これを行う最も簡単な方法は次のとおりです。
public class MyService extends Service {
private final IBinder localBinder = new LocalBinder();
public void onCreate() {
super.onCreate();
// first time the service is bound, it will be created
// you can start up your timed-operations here
}
public IBinder onBind(Intent intent) {
return localBinder;
}
public void onUnbind(Intent intent) {
// called when the last Activity is unbound from this service
// stop your timed operations here
}
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
}