androidサービスの使用(三)-activityとのインタラクション


本文は主にactivityがどのようにサービスとインタラクティブになるかを話して、このインタラクティブはとてもよくて、例えば1つの音楽プレーヤーの中で、サービスは音楽の再生を担当して、activityはフロントエンドのUIを担当して、あなたがフロントエンドで進度を調節する時、サービスに1つのコマンドを出す必要があって、サービスは音楽の進度を放送しても直ちにactivityに戻って、activityの進度のバーが後ろにスライドすることができるようにします.本文で参考にしたのは公式サイトです.上に詳細な例がありますが、ここでは詳しく説明しません.
1サービスとactivityは同じプロセスでIBinderを使用します
Activityがサービスと対話する必要がある場合、サービスの第2の起動方式、すなわち
bindService()は、avtivity(正確にはclientsです.他のコンポーネントもserviceにバインドできるため)とserviceをバインドします.一方,サービスは独自のIBinderクラスを作成し,Binder,overrideというクラスのonBind()メソッドを継承し,このメソッドではこのIBinderインスタンスをclientsに返す必要がある.一方、clientsは、内部匿名クラスであるServiceConnectionオブジェクトを実装する必要があり、clientsは、このServiceConnectionのonServiceConnected()メソッドを使用してこのIBinderインスタンスを取得し、このIBinderのメソッドを使用してサービスのインスタンスを取得し、サービスのpublicメソッドにアクセスすることができる.
この方法はサービスがactivityのバックグラウンドでしか機能しないことに非常に適しており,この方法は適切であることを改めて強調した.
同じプロセスのactivityとserviceでは、manifestでandroid:processプロパティを別途宣言しない限り、デフォルトでのserviceとactivityは同じプロセスにあります.
しかも例では
义齿
メッセージを送信し、サービスがactivityにメッセージを送信するのはまだ見つかっていないので、スラグはブロードキャストが可能だと考えています.
ここでは、activityがIBinderを介してサービスを呼び出す方法の例があります.まず、サービスでIBinderクラスのインスタンスを宣言し、onBind時にclientsにこのIBinderオブジェクトを返します.clientsはonServiceConnected()でIBinderインスタンスを取得できます.コードは次のとおりです.
public class LocalService extends Service {
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();
    // Random number generator
    private final Random mGenerator = new Random();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /** method for clients */
    public int getRandomNumber() {
      return mGenerator.nextInt(100);
    }
}

Activityの使用:
public class BindingActivity extends Activity {
    LocalService mService;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    /** Called when a button is clicked (the button in the layout file attaches to
      * this method with the android:onClick attribute) */
    public void onButtonClick(View v) {
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            int num = mService.getRandomNumber();
            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
        }
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}

2サービスとactivityは同じプロセスではありません
(1)Messagerを使って、
これは最も簡単なIPCで、サービスで異なるMessageオブジェクトを処理するためにHandlerを定義します.
(2)AIDLの使用
スラグはまだ使っていないので、しばらく止めて、後で勉強したらブログを更新し続けます.