Service官方教程(7)Bound Service示例之1-同进程下直接继承Service

Extending the Binder class

  If your service is used only by the local application and does not need to work across processes, then you can implement your own Binder class that provides your client direct access to public methods in the service.

  Note: This works only if the client and service are in the same application and process, which is most common. For example, this would work well for a music application that needs to bind an activity to its own service that's playing music in the background.

  Here's how to set it up:步骤如下

  1. In your service, create an instance of Binder that either:
    • contains public methods that the client can call
    • returns the current Service instance, which has public methods the client can call
    • or, returns an instance of another class hosted by the service with public methods the client can call
  2. Return this instance of Binder from the onBind() callback method.
  3. In the client, receive the Binder from the onServiceConnected() callback method and make calls to the bound service using the methods provided.

  Note: The reason the service and client must be in the same application is so the client can cast the returned object and properly call its APIs. The service and client must also be in the same process, because this technique does not perform any marshalling across processes.

  For example, here's a service that provides clients access to methods in the service through a Binder implementation:

 1 public class LocalService extends Service {
 2 
 3     // Binder given to clients
 4     private final IBinder mBinder = new LocalBinder();
 5     
 6     // Random number generator
 7     private final Random mGenerator = new Random();
 8 
 9     /**
10      * Class used for the client Binder.  Because we know this service always
11      * runs in the same process as its clients, we don't need to deal with IPC.
12      */
13     public class LocalBinder extends Binder {
14         LocalService getService() {
15             // Return this instance of LocalService so clients can call public methods
16             return LocalService.this;
17         }
18     }
19 
20     @Override
21     public IBinder onBind(Intent intent) {
22         return mBinder;
23     }
24 
25     /** method for clients */
26     public int getRandomNumber() {
27         return mGenerator.nextInt(100);
28     }
29 }

  The LocalBinder provides the getService() method for clients to retrieve the current instance of LocalService. This allows clients to call public methods in the service. For example, clients can call getRandomNumber() from the service.

  Here's an activity that binds to LocalService and calls getRandomNumber() when a button is clicked:

 1 public class BindingActivity extends Activity {
 2 
 3     LocalService mService;
 4     boolean mBound = false;
 5 
 6     @Override
 7     protected void onCreate(Bundle savedInstanceState) {
 8         super.onCreate(savedInstanceState);
 9         setContentView(R.layout.activity_binding);
10     }
11 
12     @Override
13     protected void onStart() {
14         super.onStart();
15 
16         // Bind to LocalService
17         Intent intent = new Intent(this, LocalService.class);
18         bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
19     }
20 
21     @Override
22     protected void onStop() {
23         super.onStop();
24         // Unbind from the service
25         if (mBound) {
26             unbindService(mConnection);
27             mBound = false;
28         }
29     }
30 
31     /** Called when a button is clicked (the button in the layout file attaches to
32      * this method with the android:onClick attribute) */
33     public void onButtonClick(View v) {
34         if (mBound) {
35             // Call a method from the LocalService.
36             // However, if this call were something that might hang, then this request should
37             // occur in a separate thread to avoid slowing down the activity performance.
38             int num = mService.getRandomNumber();
39             Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
40         }
41     }
42 
43     /** Defines callbacks for service binding, passed to bindService() */
44     private ServiceConnection mConnection = new ServiceConnection() {
45 
46         @Override
47         public void onServiceConnected(ComponentName className,
48                                        IBinder service) {
49             // We've bound to LocalService, cast the IBinder and get LocalService instance
50             LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
51             mService = binder.getService();
52             mBound = true;
53         }
54 
55         @Override
56         public void onServiceDisconnected(ComponentName arg0) {
57             mBound = false;
58         }
59     };
60 }

  The above sample shows how the client binds to the service using an implementation of ServiceConnection and the onServiceConnected() callback. The next section provides more information about this process of binding to the service.

  Note: In the example above, the onStop() method unbinds the client from the service. Clients should unbind from services at appropriate times, as discussed in Additional Notes.

  For more sample code, see the LocalService.java class and the LocalServiceActivities.java class in ApiDemos.

 

posted @ 2016-09-23 15:09  f9q  阅读(208)  评论(0编辑  收藏  举报