AIDL使用Service の抽象クラス

前回の投稿「AIDL バインド使用を簡単にすることを検討」では呼び出し側を書いたので、Service 側の方を抽象クラスを用意する。

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
 * BaseService.
 *  総称型 S は、AIDLインターフェースの Stub を指定する。
 */

public abstract class BaseService<S extends IBinder> extends Service{
   private S stub;
   protected abstract S createStub();

   @Override
   public final IBinder onBind(Intent intent){
      stub = createStub();
      onBindSuport(intent);
      return stub;
   }

   // onBind の処理を書く場合、これをオーバーライドする
   public void onBindSuport(Intent intent){
   }

   @Override
   public void onRebind(Intent intent){
      stub = createStub();
   }
   @Override
   public boolean onUnbind(Intent intent){
      // 次回バインド時に onRebild が呼ばれる
      stub = null;
      return true;
   }
}

例)Service バインドのインターフェースが ISampleService.aidl の場合、
    ISampleService.Stub が総称型になり、以下のように記述する。

public class  MyService extends BaseService<ISampleService.Stub> {

    @Override
    protected Stub createStub(){
       return new ISampleService.Stub(){
          // クライアントが参照できるメソッドの実装
       };
    }

のようにする。