Service的绑定过程

Service的绑定过程

服务的绑定也算是开发中比较常用的功能,在上下文环境中通过bindService就可以绑定一个服务,通过追踪bindService的源码可以知道,最后会调用到父类ContextWrapper中,在这个类中又调用了mBase的bindService方法,mBase的实现是ContextImpl《Context创建》,部分源码如下(ContextWrapper中):

//Context类型,具体实现类是ContextImpl
Context mBase;
  
@Override
public boolean bindService(Intent service, ServiceConnection conn,
        int flags) {
    return mBase.bindService(service, conn, flags);
}

由于bindService的具体实现是在ContextImpl类中,那么就来查看下ContextImpl的bindService方法:

@Override
public boolean bindService(Intent service, ServiceConnection conn,
            int flags) {
    warnIfCallingFromSystemProcess();
    return bindServiceCommon(service, conn, flags, mMainThread.getHandler(), getUser());
}

ContextImpl的bindService方法又调用了bindServiceCommon方法:

private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
       handler, UserHandle user) {
   ...............
   
   try {
       .............
       
       //关键代码1
       int res = ActivityManager.getService().bindService(
           mMainThread.getApplicationThread(), getActivityToken(), service,
           service.resolveTypeIfNeeded(getContentResolver()),
           sd, flags, getOpPackageName(), user.getIdentifier());
           
       .............
   } catch (RemoteException e) {
       throw e.rethrowFromSystemServer();
   }
}

在关键代码1处,ActivityManager.getService()是AMS的代理对象,这里通过跨进程通信调用到了AMS的方法中,查看下AMS的bindService方法:

public int bindService(IApplicationThread caller, IBinder token, Intent service,
            String resolvedType, IServiceConnection connection, int flags, String callingPackage,
            int userId) throws TransactionTooLargeException {
        enforceNotIsolatedCaller("bindService");
		..................
		
        synchronized(this) {
            return mServices.bindServiceLocked(caller, token, service,
                    resolvedType, connection, flags, callingPackage, userId);
        }
}

在上述方法中,又调用了ActiveServices的bindServiceLocked方法:

int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
            String resolvedType, final IServiceConnection connection, int flags,
            String callingPackage, final int userId) throws TransactionTooLargeException {
            ......................
            
	        if (s.app != null && b.intent.received) {
	                try {
	                    c.conn.connected(s.name, b.intent.binder, false);
	                } catch (Exception e) {
	                    Slog.w(TAG, "Failure sending service " + s.shortName
	                            + " to connection " + c.conn.asBinder()
	                            + " (in " + c.binding.client.processName + ")", e);
	                }
	
	                // If this is the first app connected back to this binding,
	                // and the service had previously asked to be told when
	                // rebound, then do so.
	                if (b.intent.apps.size() == 1 && b.intent.doRebind) {
	                
						//关键代码2
	                    requestServiceBindingLocked(s, b.intent, callerFg, true);
	                }
	         } else if (!b.intent.requested) {
	         
	      		    //关键代码3
	                requestServiceBindingLocked(s, b.intent, callerFg, false);
	         }
	      ......................
}

在关键代码2和关键代码3处,调用了requestServiceBindingLocked方法:

private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
            boolean execInFg, boolean rebind) throws TransactionTooLargeException {
        if (r.app == null || r.app.thread == null) {
            // If service is not currently running, can't yet bind.
            return false;
        }
        if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
                + " rebind=" + rebind);
        if ((!i.requested || rebind) && i.apps.size() > 0) {
            try {
                bumpServiceExecutingLocked(r, execInFg, "bind");
                r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);

				//关键代码4
                r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
                        r.app.repProcState);
                        
                if (!rebind) {
                    i.requested = true;
                }
                i.hasBound = true;
                i.doRebind = false;
            } catch (TransactionTooLargeException e) {
                // Keep the executeNesting count accurate.
                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
                final boolean inDestroying = mDestroyingServices.contains(r);
                serviceDoneExecutingLocked(r, inDestroying, inDestroying);
                throw e;
            } catch (RemoteException e) {
                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
                // Keep the executeNesting count accurate.
                final boolean inDestroying = mDestroyingServices.contains(r);
                serviceDoneExecutingLocked(r, inDestroying, inDestroying);
                return false;
            }
        }
        return true;
}

在关键代码4处,r.app.thread是ApplicaitonThread的代理对象,这里是AMS向客户端发起了跨进程通信请求,调用ApplicaitonThread中的scheduleBindService方法:

public final void scheduleBindService(IBinder token, Intent intent,
         boolean rebind, int processState) {
     updateProcessState(processState, false);
     BindServiceData s = new BindServiceData();
     s.token = token;
     s.intent = intent;
     s.rebind = rebind;

     if (DEBUG_SERVICE)
         Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
                 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
     
     //关键代码5
     sendMessage(H.BIND_SERVICE, s);
}

在关键代码5处,发送了一个绑定服务的消息给H,H类中的handleMessage方法:

case BIND_SERVICE:
          Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
          handleBindService((BindServiceData)msg.obj);
          Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
          break;

在H类中收到绑定服务消息后又调用了ActivityThread的handleBindService方法:

private void handleBindService(BindServiceData data) {
        Service s = mServices.get(data.token);
        if (DEBUG_SERVICE)
            Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
        if (s != null) {
            try {
                data.intent.setExtrasClassLoader(s.getClassLoader());
                data.intent.prepareToEnterProcess();
                try {
                    if (!data.rebind) {
                    
						//关键代码6
                        IBinder binder = s.onBind(data.intent);
                        ActivityManager.getService().publishService(
                                data.token, data.intent, binder);
                                
                    } else {
                        s.onRebind(data.intent);
                        ActivityManager.getService().serviceDoneExecuting(
                                data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
                    }
                    ensureJitEnabled();
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
            } catch (Exception e) {
                if (!mInstrumentation.onException(s, e)) {
                    throw new RuntimeException(
                            "Unable to bind to service " + s
                            + " with " + data.intent + ": " + e.toString(), e);
                }
            }
        }
}

在关键代码6处,调用Service的onBind方法返回binder对象,这个binder对象就是我们自己创建的(aidl的stub的实现类),然后在通过AMS的publishService方法发布该binder服务,下面看下AMS的publishService方法:

public void publishService(IBinder token, Intent intent, IBinder service) {
    // Refuse possible leaked file descriptors
    if (intent != null && intent.hasFileDescriptors() == true) {
        throw new IllegalArgumentException("File descriptors passed in Intent");
    }

    synchronized(this) {
        if (!(token instanceof ServiceRecord)) {
            throw new IllegalArgumentException("Invalid service token");
        }

		//关键代码7
        mServices.publishServiceLocked((ServiceRecord)token, intent, service);
    }
}

在关键代码7处调用了ActiveServices的publishServiceLocked方法:

void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
    final long origId = Binder.clearCallingIdentity();
         try {
			
			    //关键代码8 c.conn是IServiceConnection类型的
                c.conn.connected(r.name, service, false);
            } catch (Exception e) {
              Slog.w(TAG, "Failure sending service " + r.name +
                      " to connection " + c.conn.asBinder() +
                      " (in " + c.binding.client.processName + ")", e);
            }
}

关键代码8处的c.conn的类型是IServiceConnection,它的具体实现是LoadedApk的内部类ServiceDispatcher的内部类InnerConnection:

public final class LoadedApk {
	
	  ...................
	  
      static final class ServiceDispatcher {
		 
			 ...................
		 
              private final ServiceDispatcher.InnerConnection mIServiceConnection;
             
              //关键代码9
              private static class InnerConnection extends IServiceConnection.Stub {
        		    final WeakReference mDispatcher;

		            InnerConnection(LoadedApk.ServiceDispatcher sd) {
		                  mDispatcher = new WeakReference(sd);
           		    }

		            public void connected(ComponentName name, IBinder service, boolean dead)
		                    throws RemoteException {
		                LoadedApk.ServiceDispatcher sd = mDispatcher.get();
		                if (sd != null) {
		                
							//关键代码10
		                    sd.connected(name, service, dead);
		                }
		            }
             }


	   	//LoadedApk.ServiceDispatcher的connected方法
		 public void connected(ComponentName name, IBinder service, boolean dead) {
            if (mActivityThread != null) {
				//关键代码11
                mActivityThread.post(new RunConnection(name, service, 0, dead));
            } else {
				//关键代码12
                doConnected(name, service, dead);
            }
         }
     }
}

在关键代码9处InnerConnection具体实现了IServiceConnection.Stub,IServiceConnection是个aidl接口,所以InnerConnection具备跨进程通信的能力,而在关键代码8处connected方法的调用其实就是调用了InnerConnection的connected方法,在connected方法中的关键代码10处调用了sd的connected方法,sd是LoadedApk.ServiceDispatcher类型的,在sd的connected方法中的关键代码11处mActivityThread是一个Handler(其真身是ActivityThread中的H),通过H将程序回调到主线程中执行,由于RunConnection是个Runnable,所以会执行RunConnection的run方法,RunConnection源码如下:

private final class RunConnection implements Runnable {
        RunConnection(ComponentName name, IBinder service, int command, boolean dead) {
            mName = name;
            mService = service;
            mCommand = command;
            mDead = dead;
        }

        public void run() {
            if (mCommand == 0) {
				//关键代码13
                doConnected(mName, mService, mDead);
            } else if (mCommand == 1) {
                doDeath(mName, mService);
            }
        }

        final ComponentName mName;
        final IBinder mService;
        final int mCommand;
        final boolean mDead;
}

由关键代码12和关键代码13可知,最终程序会执行到ServiceDispatcher的doConnected方法中,doConnected源码如下:

public void doConnected(ComponentName name, IBinder service, boolean dead) {
       .......................
        // If there was an old service, it is now disconnected.
        if (old != null) {
            mConnection.onServiceDisconnected(name);
        }
        if (dead) {
            mConnection.onBindingDied(name);
        }
        // If there is a new viable service, it is now connected.
        if (service != null) {
		
			//关键代码14
            mConnection.onServiceConnected(name, service);
        } else {
            // The binding machinery worked, but the remote returned null from onBind().
            mConnection.onNullBinding(name);
        }
}

由关键代码14处可知,调用了mConnection的onServiceConnected方法,而mConnection的类型是ServiceConnection,其实这个mConnection对象就是我们binderService方法中传递的自己创建的ServiceConnection对象,由于该对象无法进行跨进程通信,所以在需要跟AMS进行跨进程通信的时候用的都是一个跟它相对应的InnerConnection对象,客户端同时持有了这两个对象,这样需要跨进程的时候就使用InnerConnection,我们在客户端绑定服务时会向AMS发起跨进程通信,AMS处理完毕会回调InnerConnection的connected方法,在connected方法中就会调用客户端传入的ServiceConnection对象的onServiceConnected方法,这样服务的绑定就完成了。

你可能感兴趣的:(Android)