Android Service系列(二十一)Binding to a service

    xiaoxiao2024-12-06  69

    Application components (clients) can bind to a service by calling bindService(). The Android system then calls the service's onBind() method, which returns an IBinder for interacting with the service.

    The binding is asynchronous, and bindService() returns immediately without returning the IBinder to the client. To receive the IBinder, the client must create an instance of ServiceConnection and pass it to bindService(). The ServiceConnection includes a callback method that the system calls to deliver the IBinder.

    翻译:bindService onBind IBinder  asynchronous ,return immediately, ServicConnection ,

     

    Note: Only activities, services, and content providers can bind to a service—you can't bind to a service from a broadcast receiver.

    注意:只有activity,service,以及content provider 可以bind to a service ,broadcast receiver不能bind to a service

     

     

    To bind to a service from your client, follow these steps:

    Implement ServiceConnection.

    Your implementation must override two callback methods:

    onServiceConnected()

    The system calls this to deliver the IBinder returned by the service's onBind() method.

            翻译:通过这个方法系统传递IBinder

      onServiceDisconnected()

         The Android system calls this when the connection to the service is unexpectedly lost, such as when the service has          crashed or has been killed. This is not called when the client unbinds.

             翻译:注意onServiceDisconnected 方法只有异常lost的时候才会调用。

     

        2. Call bindService(), passing the ServiceConnection implementation. 

             Note: If the method returns false, your client does not have a valid connection to the service. However, your client should           still call unbindService(); otherwise, your client will keep the service from shutting down when it is idle.

            翻译:注意:如果这个bindService 方法返回false,表明无法连接成功,然而unbindService还是要调用,否则。这个客户端会阻止service关闭。

          3.When the system calls your onServiceConnected() callback method, you can begin making calls to the service, using the methods defined by the interface.

          翻译:当调用onServiceConnected方法后,你可以调用service的方法了。

     

          4.To disconnect from the service, call unbindService().

           If your client is still bound to a service when your app destroys the client, destruction causes the client to unbind. It is better practice to unbind the client as soon as it is done interacting with the service. Doing so allows the idle service to shut down. For more information about appropriate times to bind and unbind, see Additional notes.

           翻译:client销毁的时候会unbind. 最好和service交互完后就立刻解绑。 这样可以让闲置的service shut down.

    参考:Additional notes.

     

    The following example connects the client to the service created above by extending the Binder class, so all it must do is cast the returned IBinder to the LocalService class and request the LocalService instance:

    翻译:把IBinder强转成LocalService。

    LocalService mService; private ServiceConnection mConnection = new ServiceConnection() { // Called when the connection with the service is established public void onServiceConnected(ComponentName className, IBinder service) { // Because we have bound to an explicit // service that is running in our own process, we can // cast its IBinder to a concrete class and directly access it. LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } // Called when the connection with the service disconnects unexpectedly public void onServiceDisconnected(ComponentName className) { Log.e(TAG, "onServiceDisconnected"); mBound = false; } };

    With this ServiceConnection, the client can bind to a service by passing it to bindService(), as shown in the following example:

    翻译:把ServiceConnection 传给bindService方法。如下:

    Intent intent = new Intent(this, LocalService.class); bindService(intent, connection, Context.BIND_AUTO_CREATE);

    The first parameter of bindService() is an Intent that explicitly names the service to bind.

    Caution: If you use an intent to bind to a Service, ensure that your app is secure by using an explicit intent. Using an implicit intent to start a service is a security hazard because you can't be certain what service will respond to the intent, and the user can't see which service starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call bindService() with an implicit intent.

    翻译:Android 5.0以后,bindService不能再用隐式意图了,否则会抛出异常。

    The second parameter is the ServiceConnection object. The third parameter is a flag indicating options for the binding. It should usually be BIND_AUTO_CREATE in order to create the service if it's not already alive. Other possible values are BIND_DEBUG_UNBIND and BIND_NOT_FOREGROUND, or 0 for none.

    翻译:第三个参数一般是BIND_AUTO_CREATE ==>in order to create the service if it's not already alive

     

    Additional notes

    其他注意点

    Here are some important notes about binding to a service:

    You should always trap DeadObjectException exceptions, which are thrown when the connection has broken. This is the only exception thrown by remote methods.

    翻译:注意捕捉DeadObjectException

    Objects are reference counted across processes.翻译:对象是跨进程计算的引用--------------------------------------You usually pair the binding and unbinding during matching bring-up and tear-down moments of the client's lifecycle, as described in the following examples:If you need to interact with the service only while your activity is visible, you should bind during onStart()and unbind during onStop().If you want your activity to receive responses even while it is stopped in the background, then you can bind during onCreate() and unbind during onDestroy(). Beware that this implies that your activity needs to use the service the entire time it's running (even in the background), so if the service is in another process, then you increase the weight of the process and it becomes more likely that the system will kill it.

    翻译:binding 和unBinding 要和客户端的生命周期pair.  

               如果不可见的时候仍然bind,则会增加 service进程的weight,则系统更有可能杀死他。

    Note: You don't usually bind and unbind during your activity's onResume() and onPause(), because these callbacks occur at every lifecycle transition and you should keep the processing that occurs at these transitions to a minimum. Also, if multiple activities in your application bind to the same service and there is a transition between two of those activities, the service may be destroyed and recreated as the current activity unbinds (during pause) before the next one binds (during resume). This activity transition for how activities coordinate their lifecycles is described in the Activities document.

    注意,在onResume和onPause里面bind,unbind也不好。。。

    For more sample code, showing how to bind to a service, see the RemoteService.java class in ApiDemos.

    参考: the RemoteService.java class in ApiDemos.

     

    最新回复(0)