メモ > Service

「メモ/Service」の編集履歴(バックアップ)一覧に戻る
メモ/Service」を以下のとおり復元します。
* 概要
UIを持たないがライフサイクルが通常より長いアプリケーション。
mp3プレイヤーのバックエンドなどに適している。

* 作成手順

** aidlを書く
他のJavaソースファイルと同じ位置に IHogeService.aidl を作成する。中身はこんな感じ
 package jp.hoge.HogePackage;
 interface IHogeService{
     int getPid();
 }

** インタフェースの実装クラスを書く
API Demos のサンプルコードを参照

** 呼び出し側を書く
 private Intent mServiceIntent = null;
 private IHogeService mService = null;
 private boolean mBound = false;
 private ServiceConnection mConnection = new ServiceConnection(){
    // サービスと接続した
    public void onServiceConnected(ComponentName className, IBinder service){
        mService = IHogeService.Stub.asInterface(service);
        mBound = true;
        try{
            Log.d("Hoge","service connected. pid="+mService.getPid());
        }catch(DeadObjectException e){}
    }
    // サービスと切断した
    public void onServiceDisconnected(ComponentName className){
        Log.d("Hoge","service disconnected.");
        mService = null;
        mBound = false;
    }
 };
 private void bindIRCService(){
    if( mServiceIntent == null ) mServiceIntent = new Intent(this,HogeService.class);
    // サービスを開始して
    android.content.ComponentName cn = startService(mServiceIntent, null);
    // 普通にバインド可能か?
    boolean r = bindService (mServiceIntent,null,mConnection,0);
    Log.d("Hoge","bind service.."+(r?"OK":"NG"));
 }
 private void unbindIRCService(boolean bStop){
    if( mBound ){
        mBound = false;
        unbindService(mConnection);
        Log.d("Hoge","unbind service.");
    }
    if( bStop ) stopService(mServiceIntent);
 }
 private void killIRCService(){
    if( mService == null ) return;
    try {
        Process.killProcess(mService.getPid());
    }catch (DeadObjectException ex){
        mService = null;
        Log.d("Hoge","killService :DeadObjectException");
    }
 }

復元してよろしいですか?

ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。