メモ > Service

概要

UIを持たないがライフサイクルが通常より長いアプリケーション。
mp3プレイヤーのバックエンドなどに適している。

作成手順


aidlを書く

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

インタフェースの実装クラスを書く

API Demos のサンプルコードを参照

AndroidManifest.xml にサービスを定義する

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="jp.hoge.HogePackage">
   <application>
       <service class=".HogeService" android:process=":remote" />

android:process=":remote" をつけると別プロセスで動くようになる。
利点とかはまだよくわからない。

呼び出し側を書く

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");
   }
}

サービスとの連携

サービスがバルーンやダイアログを出したい場合はNotificationManagerを使う。
Activityがサービスからの通知を受け取りたい場合は IntentReceiver を使う?(未確認)

システムが提供するサービス

Context.getSystemService(String name)を使って、システムが提供するサービスを利用できる。

Context.WINDOW_SERVICE ("window")
The top-level window manager in which you can place custom windows. The returned object is a ViewManager.
Context.INFLATE_SERVICE ("inflate")
A ViewInflate for inflating layout resources in this context.
Context.POWER_SERVICE ("power")
A PowerManager for controlling power management.
Context.ALARM_SERVICE ("alarm")
AlarmManagerは指定したタイミングでIntentを送る。
Context.NOTIFICATION_SERVICE ("notification")
NotificationManagerはバックグラウンドのイベントをユーザに通知できるようにする。
Context.KEYGUARD_SERVICE ("keyguard")
A KeyguardManager for controlling keyguard.
Context.LOCATION_SERVICE ("location")
A LocationManager for controlling location (e.g., GPS) updates.

タグ:

+ タグ編集
  • タグ:
最終更新:2007年11月16日 12:03
ツールボックス

下から選んでください:

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