bindService()是Context的一个方法,它是抽象的。函数原型的代码如下:(android 2.3.3)
/**
* Connect to an application service, creating it if needed. This defines
* a dependency between your application and the service. The given
* <var>conn</var> will receive the service object when its created and be
* told if it dies and restarts. The service will be considered required
* by the system only for as long as the calling context exists. For
* example, if this Context is an Activity that is stopped, the service will
* not be required to continue running until the Activity is resumed.
*
* <p>This function will throw {@link SecurityException} if you do not
* have permission to bind to the given service.
*
* <p class="note">Note: this method <em>can not be called from an
* {@link BroadcastReceiver} component</em>. A pattern you can use to
* communicate from an BroadcastReceiver to a Service is to call
* {@link #startService} with the arguments containing the command to be
* sent, with the service calling its
* {@link android.app.Service#stopSelf(int)} method when done executing
* that command. See the API demo App/Service/Service Start Arguments
* Controller for an illustration of this. It is okay, however, to use
* this method from an BroadcastReceiver that has been registered with
* {@link #registerReceiver}, since the lifetime of this BroadcastReceiver
* is tied to another object (the one that registered it).</p>
*
* @param service Identifies the service to connect to. The Intent may
* specify either an explicit component name, or a logical
* description (action, category, etc) to match an
* {@link IntentFilter} published by a service.
* @param conn Receives information as the service is started and stopped.
* @param flags Operation options for the binding. May be 0,
* {@link #BIND_AUTO_CREATE}, {@link #BIND_DEBUG_UNBIND}, or
* {@link #BIND_NOT_FOREGROUND}.
* @return If you have successfully bound to the service, true is returned;
* false is returned if the connection is not made so you will not
* receive the service object.
*
* @throws SecurityException
*
* @see #unbindService
* @see #startService
* @see #BIND_AUTO_CREATE
* @see #BIND_DEBUG_UNBIND
* @see #BIND_NOT_FOREGROUND
*/
public abstract boolean bindService(Intent service, ServiceConnection conn,
int flags);
而最终实现bindService()方法的是ContextImpl这个类,代码如下:
@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
IServiceConnection sd;
if (mPackageInfo != null) {
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
mMainThread.getHandler(), flags);
} else {
throw new RuntimeException("Not supported in system context");
}
try {
int res = ActivityManagerNative.getDefault().bindService(
mMainThread.getApplicationThread(), getActivityToken(),
service, service.resolveTypeIfNeeded(getContentResolver()),
sd, flags);
if (res < 0) {
throw new SecurityException(