Android services allow long-running tasks to perform work in the background independently of an application's user interface. There are two main types of services: started services which can perform operations indefinitely even if the starting component is destroyed, and bound services which offer a client-server interface between a component and the service. Services must be started with startService() or bound to with bindService() and have lifecycle callback methods like onStartCommand(), onBind(), onCreate(), and onDestroy(). The IntentService class simplifies started service implementation. Bound services can expose interfaces using Binder, Messenger, or AIDL to allow inter-process communication.
19. 2. Ibinder の定義 bind 時に Service から取得する何か ServiceConnection.onServiceConnection() コールバック経由 Service との通信は IBinder を介して行う 実際は Service.onBind() の戻り値 どのようなアクセス法を提供するかは onBind() の実装で決定できる
20. 3. やってみる Service 側の定義 public class MyService extends Service { (略) @Override public IBinder onBind(Intent intent) { return new LocalBinder(); } class LocalBinder extends Binder { MyService getService() { return MyService.this; } } public void somemethod() { // 呼び出される Service 側のメソッド } }
21. 3. やってみる 呼び出し側の定義 public class MyActivity extends Activity { (略) MyService myservice; private void startServiceMethod(){ // どっかから呼んでもらう Intent i = new Intent( this, MyService.class); bindService(i, conn, Context.BIND_AUTO_CREATE); } private void someServiceCall(){ // どっかから呼んでもらう myservice.somemethod(); } private MyConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder binder) { myservice = ((MyService.LocalBinder)binder).getService(); } @Override public void onServiceDisconnected(ComponentName name) { myservice = null; } } }
23. 1. サービスの種類 Local Service 同一プロセス内の Service そのプロセス内で start したもの 直接 Service の参照を取得できる 今までの手法 AIDL いらない Remote Service 他プロセスになっている Service 他のアプリケーション , パッケージで start したもの 直接 Service の参照を取得できない AIDL 必要