注意:通常,客户端和服务端只是在同一个应用和进程中工作,例如,对于一个要良好工作的播放音乐的应用程序,就需要把在后台工作的播放音乐的服务与应用自己的一个Activity绑定。

以下是建立绑定类型服务的步骤:

1. 在服务中,使用以下方法之一创建Binder实例:

   A. 包含客户端能够调用的公共方法;

   B. 返回当前服务的实例,它有客户端能够调用的公共方法;

   C. 或者返回一个带有客户端能够调用的公共方法的被服务持有的另一个类。

2.  从onBind()回调方法中返回这个Binder对象的实例;

3.  在客户端,在onServiceConnected()回调方法中接收Binder对象,并且使用这个对象提供的方法来调用被绑定的服务。

注意:服务端和客户端必须在同一个应用中的原因是:这样的客户端能够转换返回的对象,并正确的调用自己的APIs。服务端和客户端也必须是在同一个进程中,因为这种技术不执行任何跨进程处理。

例如,以下服务端代码提供了通过Binder实现访问服务端方法的能力:

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);
     }
 }以上代码中的LocalBinder对象给客户端提供了getService()方法,用这个方法客户端能够获取LocalService服务的当前实例。这样就允许客户端调用服务中的公共方法。例如,客户端能够调用服务端的getRandomNumber()方法。
以下Activity代码绑定了LocalService服务,并且在点击一个按钮时调用了服务的getRandomNumber()方法:
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;
         }
     };
 }以上实例显示了客户端时怎样使用ServiceConnection接口和onServiceConnected回调方法的实现来绑定服务的。在接下来的章节中会提供更多的关于绑定服务进程的信息。
注意:上例中没有明确解除绑定的服务端,但是,所有的客户端都应该在合适的时机解除绑定(如在Activity暂停时)。
 
示例代码:LocalService.java
/*
  * Copyright (C) 2007 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */

 package com.example.android.apis.app;

 import android.app.Notification;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Service;
 import android.content.Intent;
 import android.os.Binder;
 import android.os.IBinder;
 import android.util.Log;
 import android.widget.Toast;

 // Need the following import to get access to the app resources, since this
 // class is in a sub-package.
 import com.example.android.apis.R;

 /**
  * This is an example of implementing an application service that runs locally
  * in the same process as the application.  The {@link LocalServiceActivities.Controller}
  * and {@link LocalServiceActivities.Binding} classes show how to interact with the
  * service.
  *
  * <p>Notice the use of the {@link NotificationManager} when interesting things
  * happen in the service.  This is generally how background services should
  * interact with the user, rather than doing something more disruptive such as
  * calling startActivity().
  */
 public class LocalService extends Service {
     private NotificationManager mNM;

     // Unique Identification Number for the Notification.
     // We use it on Notification start, and to cancel it.
     private int NOTIFICATION = R.string.local_service_started;

     /**
      * Class for clients to access.  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 LocalService.this;
         }
     }

     @Override
     public void onCreate() {
         mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

         // Display a notification about us starting.  We put an icon in the status bar.
         showNotification();
     }

     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
         Log.i("LocalService", "Received start id " + startId + ": " + intent);
         // We want this service to continue running until it is explicitly
         // stopped, so return sticky.
         return START_STICKY;
     }

     @Override
     public void onDestroy() {
         // Cancel the persistent notification.
         mNM.cancel(NOTIFICATION);

         // Tell the user we stopped.
         Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
     }

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

     // This is the object that receives interactions from clients.  See
     // RemoteService for a more complete example.
     private final IBinder mBinder = new LocalBinder();

     /**
      * Show a notification while this service is running.
      */
     private void showNotification() {
         // In this sample, we'll use the same text for the ticker and the expanded notification
         CharSequence text = getText(R.string.local_service_started);

         // Set the icon, scrolling text and timestamp
         Notification notification = new Notification(R.drawable.stat_sample, text,
                 System.currentTimeMillis());

         // The PendingIntent to launch our activity if the user selects this notification
         PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                 new Intent(this, LocalServiceActivities.Controller.class), 0);

         // Set the info for the views that show in the notification panel.
         notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                        text, contentIntent);

         // Send the notification.
         mNM.notify(NOTIFICATION, notification);
     }
 } 
LocalServiceActivities.java
 /* 
 
  * Copyright (C) 2007 The Android Open Source Project 
 
  * 
 
  * Licensed under the Apache License, Version 2.0 (the "License"); 
 
  * you may not use this file except in compliance with the License. 
 
  * You may obtain a copy of the License at 
 
  * 
 
  *      http://www.apache.org/licenses/LICENSE-2.0 
 
  * 
 
  * Unless required by applicable law or agreed to in writing, software 
 
  * distributed under the License is distributed on an "AS IS" BASIS, 
 
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 
  * See the License for the specific language governing permissions and 
 
  * limitations under the License. 
 
  */ 
 

 package com.example.android.apis.app; 
 

 import com.example.android.apis.R; 
 

 import android.app.Activity; 
 
 import android.content.ComponentName; 
 
 import android.content.Context; 
 
 import android.content.Intent; 
 
 import android.content.ServiceConnection; 
 
 import android.os.Bundle; 
 
 import android.os.IBinder; 
 
 import android.view.View; 
 
 import android.view.View.OnClickListener; 
 
 import android.widget.Button; 
 
 import android.widget.Toast; 
 

 public class LocalServiceActivities { 
 
     /** 
 
      * <p>Example of explicitly starting and stopping the local service. 
 
      * This demonstrates the implementation of a service that runs in the same 
 
      * process as the rest of the application, which is explicitly started and stopped 
 
      * as desired.</p> 
 
      * 
 
      * <p>Note that this is implemented as an inner class only keep the sample 
 
      * all together; typically this code would appear in some separate class. 
 
      */ 
 
     public static class Controller extends Activity { 
 
         @Override 
 
         protected void onCreate(Bundle savedInstanceState) { 
 
             super.onCreate(savedInstanceState); 
 

             setContentView(R.layout.local_service_controller); 
 

             // Watch for button clicks. 
 
             Button button = (Button)findViewById(R.id.start); 
 
             button.setOnClickListener(mStartListener); 
 
             button = (Button)findViewById(R.id.stop); 
 
             button.setOnClickListener(mStopListener); 
 
         } 
 

         private OnClickListener mStartListener = new OnClickListener() { 
 
             public void onClick(View v) { 
 
                 // Make sure the service is started.  It will continue running 
 
                 // until someone calls stopService().  The Intent we use to find 
 
                 // the service explicitly specifies our service component, because 
 
                 // we want it running in our own process and don't want other 
 
                 // applications to replace it. 
 
                 startService(new Intent(Controller.this, 
 
                         LocalService.class)); 
 
             } 
 
         }; 
 

         private OnClickListener mStopListener = new OnClickListener() { 
 
             public void onClick(View v) { 
 
                 // Cancel a previous call to startService().  Note that the 
 
                 // service will not actually stop at this point if there are 
 
                 // still bound clients. 
 
                 stopService(new Intent(Controller.this, 
 
                         LocalService.class)); 
 
             } 
 
         }; 
 
     } 
 

     // ---------------------------------------------------------------------- 
 

     /** 
 
      * Example of binding and unbinding to the local service. 
 
      * This demonstrates the implementation of a service which the client will 
 
      * bind to, receiving an object through which it can communicate with the service.</p> 
 
      * 
 
      * <p>Note that this is implemented as an inner class only keep the sample 
 
      * all together; typically this code would appear in some separate class. 
 
      */ 
 
     public static class Binding extends Activity { 
 
         private boolean mIsBound; 
 

         private LocalService mBoundService; 
 

         private ServiceConnection mConnection = new ServiceConnection() { 
 
             public void onServiceConnected(ComponentName className, IBinder service) { 
 
                 // This is called when the connection with the service has been 
 
                 // established, giving us the service object we can use to 
 
                 // interact with the service.  Because we have bound to a explicit 
 
                 // service that we know is running in our own process, we can 
 
                 // cast its IBinder to a concrete class and directly access it. 
 
                 mBoundService = ((LocalService.LocalBinder)service).getService(); 
 

                 // Tell the user about this for our demo. 
 
                 Toast.makeText(Binding.this, R.string.local_service_connected, 
 
                         Toast.LENGTH_SHORT).show(); 
 
             } 
 

             public void onServiceDisconnected(ComponentName className) { 
 
                 // This is called when the connection with the service has been 
 
                 // unexpectedly disconnected -- that is, its process crashed. 
 
                 // Because it is running in our same process, we should never 
 
                 // see this happen. 
 
                 mBoundService = null; 
 
                 Toast.makeText(Binding.this, R.string.local_service_disconnected, 
 
                         Toast.LENGTH_SHORT).show(); 
 
             } 
 
         }; 
 

         void doBindService() { 
 
             // Establish a connection with the service.  We use an explicit 
 
             // class name because we want a specific service implementation that 
 
             // we know will be running in our own process (and thus won't be 
 
             // supporting component replacement by other applications). 
 
             bindService(new Intent(Binding.this, 
 
                     LocalService.class), mConnection, Context.BIND_AUTO_CREATE); 
 
             mIsBound = true; 
 
         } 
 

         void doUnbindService() { 
 
             if (mIsBound) { 
 
                 // Detach our existing connection. 
 
                 unbindService(mConnection); 
 
                 mIsBound = false; 
 
             } 
 
         } 
 

         @Override 
 
         protected void onDestroy() { 
 
             super.onDestroy(); 
 
             doUnbindService(); 
 
         } 
 

         private OnClickListener mBindListener = new OnClickListener() { 
 
             public void onClick(View v) { 
 
                 doBindService(); 
 
             } 
 
         }; 
 

         private OnClickListener mUnbindListener = new OnClickListener() { 
 
             public void onClick(View v) { 
 
                 doUnbindService(); 
 
             } 
 
         }; 
 

         @Override 
 
         protected void onCreate(Bundle savedInstanceState) { 
 
             super.onCreate(savedInstanceState); 
 

             setContentView(R.layout.local_service_binding); 
 

             // Watch for button clicks. 
 
             Button button = (Button)findViewById(R.id.bind); 
 
             button.setOnClickListener(mBindListener); 
 
             button = (Button)findViewById(R.id.unbind); 
 
             button.setOnClickListener(mUnbindListener); 
 
         } 
 
     } 
 
 }