Android Activity组件的启动过程

0、总图



1、总图中的第一步,Laucher主线程向ActivityManagerService进程发出START_ACTIVITY_TRANSACTION


                                                                                                                                           

       如图:第一步    

       ~/Android/frameworks/base/core/java/android/app

       ----ActivityManagerNative.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class ActivityManagerProxy implements IActivityManager  
  2. {  
  3.       
  4.     public int startActivity(IApplicationThread caller, Intent intent,  
  5.             String resolvedType, Uri[] grantedUriPermissions, int grantedMode,  
  6.             IBinder resultTo, String resultWho,  
  7.             int requestCode, boolean onlyIfNeeded,  
  8.             boolean debug) throws RemoteException {  
  9.         Parcel data = Parcel.obtain();  
  10.         Parcel reply = Parcel.obtain();  
  11.         data.writeInterfaceToken(IActivityManager.descriptor);  
  12.         data.writeStrongBinder(caller != null ? caller.asBinder() : null);  
  13.         intent.writeToParcel(data, 0);  
  14.         .........  
  15.         data.writeStrongBinder(resultTo);  
  16.         mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);  
  17.     }  
      其中caller为:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. final ApplicationThread mAppThread = new ApplicationThread();  
      继承于ApplicationThreadNative,ApplicationThreadNative继承于Binder实现了IApplicationThread。

      resultTo如下图所示:

 

        java层的Parcel,writeStrongBinder方法,最后映射到C++层,执行如下:

        ~/Android/frameworks/base/core/jni

        ----android_util_Binder.cpp

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static void android_os_Parcel_writeStrongBinder(JNIEnv* env, jobject clazz, jobject object)//clazz为Parcel,object指向了在Java层中创建的硬件访问服务FregService  
  2. {  
  3.     Parcel* parcel = parcelForJavaObject(env, clazz);//获取java层Parcel对象data的引用  
  4.     if (parcel != NULL) {  
  5.         const status_t err = parcel->writeStrongBinder(ibinderForJavaObject(env, object));  
  6.         if (err != NO_ERROR) {  
  7.             jniThrowException(env, "java/lang/OutOfMemoryError", NULL);  
  8.         }  
  9.     }  
  10. }  

       ibinderForjavaObject实现如下:

       ~/Android/frameworks/base/core/jni

       ----android_util_Binder.cpp

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)  
  2. {  
  3.     if (obj == NULL) return NULL;  
  4.   
  5.     if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {  
  6.         JavaBBinderHolder* jbh = (JavaBBinderHolder*)  
  7.             env->GetIntField(obj, gBinderOffsets.mObject);//这里把obj对象的mObject成员变量强制转为JavaBBinderHolder对象  
  8.         return jbh != NULL ? jbh->get(env) : NULL;  
  9.     }  
  10.   
  11.     if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {  
  12.         return (IBinder*)  
  13.             env->GetIntField(obj, gBinderProxyOffsets.mObject);  
  14.     }  
  15.   
  16.     LOGW("ibinderForJavaObject: %p is not a Binder object", obj);  
  17.     return NULL;  
  18. }  

     (1)如果传入的是caller.asBinder(),那么首先生成一个JavaBBinder本地对象。

     (2)如果传入的是resultTo,那么生成一个代理对象。

     

       writeStrongBinder实现如下:

       ~/Android/frameworks/base/libs/binder

       ----Parcel.cpp

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t Parcel::writeStrongBinder(const sp<IBinder>& val)  
  2. {  
  3.     return flatten_binder(ProcessState::self(), val, this);  
  4. }  

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t flatten_binder(const sp<ProcessState>& proc,  
  2.     const sp<IBinder>& binder, Parcel* out)  
  3. {  
  4.     flat_binder_object obj;  
  5.       
  6.     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;  
  7.     if (binder != NULL) {  
  8.         IBinder *local = binder->localBinder();  
  9.         if (!local) {  
  10.             BpBinder *proxy = binder->remoteBinder();  
  11.             if (proxy == NULL) {  
  12.                 LOGE("null proxy");  
  13.             }  
  14.             const int32_t handle = proxy ? proxy->handle() : 0;  
  15.             obj.type = BINDER_TYPE_HANDLE;  
  16.             obj.handle = handle;  
  17.             obj.cookie = NULL;  
  18.         } else {  
  19.             obj.type = BINDER_TYPE_BINDER;  
  20.             obj.binder = local->getWeakRefs();  
  21.             obj.cookie = local;  
  22.         }  
  23.     } else {  
  24.         obj.type = BINDER_TYPE_BINDER;  
  25.         obj.binder = NULL;  
  26.         obj.cookie = NULL;  
  27.     }  
  28.       
  29.     return finish_flatten_binder(binder, obj, out);  
  30. }  

     (1)如果是本地对象,obj.cookie为本地对象IBinder地址。

     (2)如果是代理对象,obj.handle为代理对象的句柄值。

       如图:第二步     

       Binder Driver:调用binder_transaction:

       ~/Android//kernel/goldfish/drivers/staging/android

       ----binder.c

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. case BINDER_TYPE_BINDER:  
  2.         case BINDER_TYPE_WEAK_BINDER: {  
  3.             struct binder_ref *ref;  
  4.             struct binder_node *node = binder_get_node(proc, fp->binder);  
  5.             if (node == NULL) {  
  6.                 node = binder_new_node(proc, fp->binder, fp->cookie);  
  7.                 ......  
  8.             }  
  9.             .......  
  10.             ref = binder_get_ref_for_node(target_proc, node);  
  11.             if (ref == NULL) {  
  12.                 return_error = BR_FAILED_REPLY;  
  13.                 goto err_binder_get_ref_for_node_failed;  
  14.             }  
  15.             if (fp->type == BINDER_TYPE_BINDER)  
  16.                 fp->type = BINDER_TYPE_HANDLE;  
  17.             else  
  18.                 fp->type = BINDER_TYPE_WEAK_HANDLE;  
  19.             fp->handle = ref->desc;  
  20.             ......  
  21.         } break;  
  22.         case BINDER_TYPE_HANDLE:  
  23.         case BINDER_TYPE_WEAK_HANDLE: {  
  24.             struct binder_ref *ref = binder_get_ref(proc, fp->handle);  
  25.             ......  
  26.             if (ref->node->proc == target_proc) {  
  27.                 if (fp->type == BINDER_TYPE_HANDLE)  
  28.                     fp->type = BINDER_TYPE_BINDER;  
  29.                 else  
  30.                     fp->type = BINDER_TYPE_WEAK_BINDER;  
  31.                 fp->binder = ref->node->ptr;  
  32.                 fp->cookie = ref->node->cookie;  
  33.                 binder_inc_node(ref->node, fp->type == BINDER_TYPE_BINDER, 0, NULL);  
  34.                 if (binder_debug_mask & BINDER_DEBUG_TRANSACTION)  
  35.                     printk(KERN_INFO "        ref %d desc %d -> node %d u%p\n",  
  36.                            ref->debug_id, ref->desc, ref->node->debug_id, ref->node->ptr);  
  37.             } else {  
  38.                 .......  
  39.             }  
  40.         } break;  
     
      (1)如果是 BINDER_TYPE_BINDER ,首先创建实体对象,再创建引用对象。handle为引用句柄值。

      (2)如果是BINDER_TYPE_HANDLE,首先获取引用对象,再获取实体对象,cookie为本地对象IBinder的地址。


        如图:第三步      

       ~/Android/frameworks/base/core/java/android/app

       ----ActivityManagerNative.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public abstract class ActivityManagerNative extends Binder implements IActivityManager  
  2. {  
  3.     ......  
  4.     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)  
  5.             throws RemoteException {  
  6.         switch (code) {  
  7.         case START_ACTIVITY_TRANSACTION:  
  8.         {  
  9.             data.enforceInterface(IActivityManager.descriptor);  
  10.             IBinder b = data.readStrongBinder();  
  11.             <span style="font-size:14px;">IApplicationThread app = ApplicationThreadNative.asInterface(b);</span>  
  12.             Intent intent = Intent.CREATOR.createFromParcel(data);  
  13.             String resolvedType = data.readString();  
  14.             ......  
  15.             IBinder resultTo = data.readStrongBinder();  
  16.             ......  
  17.             return true;  
  18.         }  


       Parcel类readStrongBinder映射到C++层,执行如下:

      ~/Android/frameworks/base/core/jni

      ----android_util_Binder.cpp

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static jobject android_os_Parcel_readStrongBinder(JNIEnv* env, jobject clazz)  
  2. {  
  3.     Parcel* parcel = parcelForJavaObject(env, clazz);//获得Java层reply的引用  
  4.     if (parcel != NULL) {  
  5.         return javaObjectForIBinder(env, parcel->readStrongBinder());  
  6.     }  
  7.     return NULL;  
  8. }  

      ~/Android/frameworks/base/libs/binder

      ----Parcel.cpp

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. sp<IBinder> Parcel::readStrongBinder() const  
  2. {  
  3.     sp<IBinder> val;  
  4.     unflatten_binder(ProcessState::self(), *this, &val);  
  5.     return val;  
  6. }  

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t unflatten_binder(const sp<ProcessState>& proc,  
  2.     const Parcel& in, sp<IBinder>* out)  
  3. {  
  4.     const flat_binder_object* flat = in.readObject(false);  
  5.       
  6.     if (flat) {  
  7.         switch (flat->type) {  
  8.             case BINDER_TYPE_BINDER:  
  9.                 *out = static_cast<IBinder*>(flat->cookie);  
  10.                 return finish_unflatten_binder(NULL, *flat, in);  
  11.             case BINDER_TYPE_HANDLE:  
  12.                 *out = proc->getStrongProxyForHandle(flat->handle);  
  13.                 return finish_unflatten_binder(  
  14.                     static_cast<BpBinder*>(out->get()), *flat, in);  
  15.         }          
  16.     }  
  17.     return BAD_TYPE;  
  18. }  


     (1)如果是BINDER_TYPE_BINDER,返回本地对象。

     (2)如果是BINDER_TYPE_HANDLE,根据句柄值,返回代理对象。


       然后执行javaObjectForIBinder。

       ~/Android/frameworks/base/core/jni

       ----android_util_Binder.cpp

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)  
  2. {  
  3.     if (val == NULL) return NULL;  
  4.   
  5.     if (val->checkSubclass(&gBinderOffsets)) {  
  6.         // One of our own!  
  7.         jobject object = static_cast<JavaBBinder*>(val.get())->object();  
  8.         ........  
  9.         return object;  
  10.     }  
  11.   
  12.     // For the rest of the function we will hold this lock, to serialize  
  13.     // looking/creation of Java proxies for native Binder proxies.  
  14.     AutoMutex _l(mProxyLock);  
  15.   
  16.     // Someone else's...  do we know about it?  
  17.     jobject object = (jobject)val->findObject(&gBinderProxyOffsets);//检查当前进程之前是否已经为它创建过一个BinderProxy对象  
  18.     if (object != NULL) {//如果有返回来的就是一个指向该BinderProxy对象的WeakReference对象object,即一个弱引用对象  
  19.         jobject res = env->CallObjectMethod(object, gWeakReferenceOffsets.mGet);//由于弱引用对象object所指向的BinderProxy对象可能已经失效,因此,需要检查它的有效性,方法是调用它的成员函数get来获得一个强引用对象。  
  20.         if (res != NULL) {//如果不为NULL  
  21.             ......  
  22.             return res;//直接返回  
  23.         }  
  24.         .....  
  25.         android_atomic_dec(&gNumProxyRefs);//如果为NULL  
  26.         val->detachObject(&gBinderProxyOffsets);//解除它与一个无效的BinderProxy对象的对应关系  
  27.         env->DeleteGlobalRef(object);//删除弱引用对象的全局引用  
  28.     }  
  29.   
  30.     object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);//创建一个BinderProxy对象  
  31.     if (object != NULL) {  
  32.         .......  
  33.         env->SetIntField(object, gBinderProxyOffsets.mObject, (int)val.get());//BinderProxy.mObject成员变量记录了这个BpBinder对象的地址  
  34.         val->incStrong(object);  
  35.   
  36.         // The native object needs to hold a weak reference back to the  
  37.         // proxy, so we can retrieve the same proxy if it is still active.  
  38.         jobject refObject = env->NewGlobalRef(  
  39.                 env->GetObjectField(object, gBinderProxyOffsets.mSelf));//获取BinderProxy内部的成员变量mSelf(BinderProxy的弱引用对象),接着再创建一个全局引用对象来引用它  
  40.         val->attachObject(&gBinderProxyOffsets, refObject,  
  41.                 jnienv_to_javavm(env), proxy_cleanup);//把它放到BpBinder里面去,下次就要使用时,就可以在上一步调用BpBinder::findObj把它找回来了  
  42.   
  43.         // Note that a new object reference has been created.  
  44.         android_atomic_inc(&gNumProxyRefs);  
  45.         incRefsCreated(env);  
  46.     }  
  47.   
  48.     return object;  
  49. }  

     (1)如果是本地对象,首先向下转型为JavaBBinder,然后取得ActivityRecord对象,它继承了IApplicationToken.Stub。而IApplicationToken.Stub继承Binder,实现了IApplicationToken。所以可以向上转型为IBinder。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. IBinder resultTo = data.readStrongBinder();  

     (2)如果是代理对象,首先生成BinderProxy对象,里面的mObject指向代理对象,向上转型为IBinder。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. IBinder b = data.readStrongBinder();  
  2. IApplicationThread app = ApplicationThreadNative.asInterface(b);  
        然后生成ActivityManagerProxy对象,里面mRemote指向BinderProxy对象。

       

        如图:第四步      
        ~/Android/frameworks/base/services/java/com/android/server/am

        ----ActivityManagerService.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public final class ActivityManagerService extends ActivityManagerNative{  
  2.   
  3.     public final int startActivity(IApplicationThread caller,  
  4.             Intent intent, String resolvedType, Uri[] grantedUriPermissions,  
  5.             int grantedMode, IBinder resultTo,  
  6.             String resultWho, int requestCode, boolean onlyIfNeeded,  
  7.             boolean debug) {  
  8.         return mMainStack.startActivityMayWait(caller, intent, resolvedType,  
  9.                 grantedUriPermissions, grantedMode, resultTo, resultWho,  
  10.                 requestCode, onlyIfNeeded, debug, nullnull);  
  11.     }  
  12.     .....  
  13. }  


         主要干了以下几件事:

     (1)根据resultTo在ActivityManagerService进程找到用来描述Laucher组件的一个ActivityRecord对象。代码如下:

        ~/Android/frameworks/base/services/java/com/android/server/am

       ----ActivityStack.java,final int startActivityLocked

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. ActivityRecord sourceRecord = null;  
  2.         if (resultTo != null) {  
  3.             int index = indexOfTokenLocked(resultTo);  
  4.             .........  
  5.             if (index >= 0) {  
  6.                 sourceRecord = (ActivityRecord)mHistory.get(index);  
  7.                 ........  
  8.             }  
  9.         }  
      (2)根据传递过来的intent创建了一个新的ActivityRecord对象,用来描述即将启动的Activity组件,即MainActivity组件。代码如下:

       ~/Android/frameworks/base/services/java/com/android/server/am

       ----ActivityStack.java,final int startActivityLocked

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,  
  2.                 intent, resolvedType, aInfo, mService.mConfiguration,  
  3.                 resultRecord, resultWho, requestCode, componentSpecified);  
     (3)由于需要在新的任务栈中启动Activity,所以设置r.task属性。代码如下:

       ~/Android/frameworks/base/services/java/com/android/server/am

       ----ActivityStack.java,startActivityUncheckedLocked

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if (r.resultTo == null && !addingToTask  
  2.                 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {  
  3.             // todo: should do better management of integers.  
  4.             ......  
  5.             r.task = new TaskRecord(mService.mCurTask, r.info, intent,  
  6.                     (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);  
  7.             ......  
  8.             newTask = true;  
  9.             if (mMainStack) {  
  10.                 mService.addRecentTaskLocked(r.task);  
  11.             }  
  12.               
  13.         }   

     (4)mHistory添加用来描述MainActivity组件的ActivityRecord对象。代码如下:

       ~/Android/frameworks/base/services/java/com/android/server/am

       ----ActivityStack.java,private final int startActivityLocked

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. final int NH = mHistory.size();  
  2.   
  3.         int addPos = -1;  
  4.           
  5.         .......  
  6.         if (addPos < 0) {  
  7.             addPos = NH;  
  8.         }  
  9.           
  10.         .......  
  11.         mHistory.add(addPos, r);  

     (5) ActivityManagerService进程向Laucher子线程发送 SCHEDULE_PAUSE_ACTIVITY_TRANSACTION 。代码如下:

       ~/Android/frameworks/base/services/java/com/android/server/am

       ----ActivityStack.java,private final void startPausingLocked

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if (prev.app != null && prev.app.thread != null) {  
  2.             ........  
  3.             try {  
  4.                 .......  
  5.                 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,  
  6.                         prev.configChangeFlags);  
  7.                 .......  
  8.             } catch (Exception e) {  
  9.                 .......  
  10.             }  
  11.         }  


2、总图中的第二步,ActivityManagerService进程向Laucher子线程发送SCHEDULE_PAUSE_ACTIVITY_TRANSACTION



      如图:第一步    

      ~/Android/frameworks/base/core/java/android/app

      ----ApplicationThreadNative.java,ApplicationThreadProxy类

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public final void schedulePauseActivity(IBinder token, boolean finished,  
  2.             boolean userLeaving, int configChanges) throws RemoteException {  
  3.         Parcel data = Parcel.obtain();  
  4.         data.writeInterfaceToken(IApplicationThread.descriptor);  
  5.         data.writeStrongBinder(token);  
  6.         data.writeInt(finished ? 1 : 0);  
  7.         data.writeInt(userLeaving ? 1 :0);  
  8.         data.writeInt(configChanges);  
  9.         mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,  
  10.                 IBinder.FLAG_ONEWAY);  
  11.         data.recycle();  
  12.     }  
       其中token是ActivityServiceManager进程的ActivityRecord对象,用来表述Lancher组件。

   

       如图:第二步,省略binder_transaction传输过程,因为上面已经分析过了。


       如图:第三步

      ~/Android/frameworks/base/core/java/android/app

      ----ApplicationThreadNative.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public abstract class ApplicationThreadNative extends Binder  
  2.         implements IApplicationThread {  
  3.     ........  
  4.     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)  
  5.             throws RemoteException {  
  6.         switch (code) {  
  7.         case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION:  
  8.         {  
  9.             data.enforceInterface(IApplicationThread.descriptor);  
  10.             IBinder b = data.readStrongBinder();  
  11.             boolean finished = data.readInt() != 0;  
  12.             boolean userLeaving = data.readInt() != 0;  
  13.             int configChanges = data.readInt();  
  14.             schedulePauseActivity(b, finished, userLeaving, configChanges);  
  15.             return true;  
  16.         }  
      其中b为一个BinderProxy的Binder代理对象,指向了ActivityManagerService中与Laucher组件对应的一个AcitivityRecord对象。


       如图:第四步

      ~/Android/frameworks/base/core/java/android/app

      ----ActivityThread.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private final class ApplicationThread extends ApplicationThreadNative {  
  2.         .......  
  3.   
  4.         public final void schedulePauseActivity(IBinder token, boolean finished,  
  5.                 boolean userLeaving, int configChanges) {  
  6.             queueOrSendMessage(  
  7.                     finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,  
  8.                     token,  
  9.                     (userLeaving ? 1 : 0),  
  10.                     configChanges);  
  11.         }  
        向Laucher主线程发送PAUSE_ACTIVITY_FINISHING命令。

      ~/Android/frameworks/base/core/java/android/app

      ----ActivityThread.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private final class H extends Handler {  
  2.        .........  
  3.        public void handleMessage(Message msg) {  
  4.            .......  
  5.            switch (msg.what) {  
  6.                ........  
  7.                case PAUSE_ACTIVITY:  
  8.                    handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);  
  9.                    .......  
  10.                    break;  
      (1)获取了ActivityClientRecord对象,在Lancher进程启动的每一个Activity组件都使用一个ActivityClientRecord对象来描述。

      (2)Laucher组件执行pause操作。

         代码如下:

      ~/Android/frameworks/base/core/java/android/app

      ----ActivityThread.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private final void handlePauseActivity(IBinder token, boolean finished,  
  2.             boolean userLeaving, int configChanges) {  
  3.         ActivityClientRecord r = mActivities.get(token);  
  4.         if (r != null) {  
  5.             //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);  
  6.             if (userLeaving) {  
  7.                 performUserLeavingActivity(r);  
  8.             }  
  9.   
  10.             r.activity.mConfigChangeFlags |= configChanges;  
  11.             Bundle state = performPauseActivity(token, finished, true);  
  12.   
  13.             // Make sure any pending writes are now committed.  
  14.             QueuedWork.waitToFinish();  
  15.               
  16.             // Tell the activity manager we have paused.  
  17.             try {  
  18.                 ActivityManagerNative.getDefault().activityPaused(token, state);  
  19.             } catch (RemoteException ex) {  
  20.             }  
  21.         }  
  22.     }  

       (3)Laucher主线程向ActivityServiceManager进程发送ACTIVITY_PAUSED_TRANSACTION。


3、Laucher主线程向ActivityServiceManager进程发送ACTIVITY_PAUSED_TRANSACTION



       如图:第一步

       ~/Android/frameworks/base/core/java/android/app

       ----ActivityManagerNative.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void activityPaused(IBinder token, Bundle state) throws RemoteException  
  2.     {  
  3.         Parcel data = Parcel.obtain();  
  4.         Parcel reply = Parcel.obtain();  
  5.         data.writeInterfaceToken(IActivityManager.descriptor);  
  6.         data.writeStrongBinder(token);  
  7.         data.writeBundle(state);  
  8.         mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0);  
  9.         reply.readException();  
  10.         data.recycle();  
  11.         reply.recycle();  
  12.     }  
        token为一个BinderProxy的Binder代理对象,指向了ActivityManagerService中与Laucher组件对应的一个AcitivityRecord对象。

       如图:第二步,省略binder_transaction传输过程,因为上面已经分析过了。


       如图:第三步

       ~/Android/frameworks/base/core/java/android/app

       ----ActivityManagerNative.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public abstract class ActivityManagerNative extends Binder implements IActivityManager  
  2. {  
  3.     ......  
  4.     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)  
  5.             throws RemoteException {  
  6.         switch (code) {  
  7.         case ACTIVITY_PAUSED_TRANSACTION: {  
  8.             data.enforceInterface(IActivityManager.descriptor);  
  9.             IBinder token = data.readStrongBinder();  
  10.             Bundle map = data.readBundle();  
  11.             activityPaused(token, map);  
  12.             reply.writeNoException();  
  13.             return true;  
  14.         }  
  15.     .......  
  16. }  
         其中token是ActivityServiceManager进程的ActivityRecord对象,用来表述Lancher组件。


        如图:第四步

        ~/Android/frameworks/base/services/java/com/android/server/am

        ----ActivityManagerService.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public final class ActivityManagerService extends ActivityManagerNative{  
  2.   
  3.     public final void activityPaused(IBinder token, Bundle icicle) {  
  4.         // Refuse possible leaked file descriptors  
  5.         if (icicle != null && icicle.hasFileDescriptors()) {  
  6.             throw new IllegalArgumentException("File descriptors passed in Bundle");  
  7.         }  
  8.   
  9.         final long origId = Binder.clearCallingIdentity();  
  10.         mMainStack.activityPaused(token, icicle, false);  
  11.         Binder.restoreCallingIdentity(origId);  
  12.     }  
  13.     .....  
  14. }  

      主要做了以下几件事:

     (1)创建MainActivity进程,即ProcessRecord对象。

       代码如下:

       ~/Android/frameworks/base/services/java/com/android/server/am

        ----ActivityManagerService.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. final ProcessRecord startProcessLocked(String processName,  
  2.             ApplicationInfo info, boolean knownToBeDead, int intentFlags,  
  3.             String hostingType, ComponentName hostingName, boolean allowWhileBooting) {  
  4.         ProcessRecord app = getProcessRecordLocked(processName, info.uid);  
  5.         .......  
  6.         if (app == null) {  
  7.             app = newProcessRecordLocked(null, info, processName);  
  8.             .......  
  9.         } else {  
  10.             ......  
  11.         }  
  12.         ......  
  13.     }  

     (2)开启MainActivity子线程。      

       ~/Android/frameworks/base/services/java/com/android/server/am

       ----ActivityManagerService.java,startProcessLocked

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int pid = Process.start("android.app.ActivityThread",  
  2.                     mSimpleProcessManagement ? app.processName : null, uid, uid,  
  3.                     gids, debugFlags, null);  

     (3)MainActivity子线程向ActivityManagerService主进程发送ATTACH_APPLICATION_TRANSACTION。

      ~/Android/frameworks/base/core/java/android/app

      ----ActivityThread.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static final void main(String[] args) {  
  2.        .....  
  3.   
  4.        Looper.prepareMainLooper();  
  5.        ......  
  6.        ActivityThread thread = new ActivityThread();  
  7.        thread.attach(false);  
  8.        ......  
  9.   
  10.        Looper.loop();  
  11.   
  12.        ......  
  13.    }  

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private final void attach(boolean system) {  
  2.         .....  
  3.         mSystemThread = system;  
  4.         if (!system) {  
  5.             ......  
  6.             IActivityManager mgr = ActivityManagerNative.getDefault();  
  7.             try {  
  8.                 mgr.attachApplication(mAppThread);  
  9.             } catch (RemoteException ex) {  
  10.             }  
  11.         }   
  12.         .....  
  13. }  



4、MainActivity子线程向ActivityManagerService主进程发送ATTACH_APPLICATION_TRANSACTION



        如图:第一步

       ~/Android/frameworks/base/core/java/android/app

       ----ActivityManagerNative.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class ActivityManagerProxy implements IActivityManager  
  2. {  
  3.       
  4.    public void attachApplication(IApplicationThread app) throws RemoteException  
  5.     {  
  6.         Parcel data = Parcel.obtain();  
  7.         Parcel reply = Parcel.obtain();  
  8.         data.writeInterfaceToken(IActivityManager.descriptor);  
  9.         data.writeStrongBinder(app.asBinder());  
  10.         mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);  
  11.         reply.readException();  
  12.         data.recycle();  
  13.         reply.recycle();  
  14.     }  
  15.     ......  
  16. }  
      app为:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. final ApplicationThread mAppThread = new ApplicationThread();  
      继承于ApplicationThreadNative,ApplicationThreadNative继承于Binder实现了IApplicationThread。

       如图:第二步,省略binder_transaction传输过程,因为上面已经分析过了。


       如图:第三步

       ~/Android/frameworks/base/core/java/android/app

       ----ActivityManagerNative.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public abstract class ActivityManagerNative extends Binder implements IActivityManager  
  2. {  
  3.     ......  
  4.     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)  
  5.             throws RemoteException {  
  6.         switch (code) {  
  7.         case ATTACH_APPLICATION_TRANSACTION: {  
  8.             data.enforceInterface(IActivityManager.descriptor);  
  9.             IApplicationThread app = ApplicationThreadNative.asInterface(  
  10.                     data.readStrongBinder());  
  11.             if (app != null) {  
  12.                 attachApplication(app);  
  13.             }  
  14.             reply.writeNoException();  
  15.             return true;  
  16.         }  
  17.     .......  
  18. }  
      首先生成BinderProxy对象,里面的mObject指向代理对象,向上转型为IBinder。
      然后生成ActivityManagerProxy对象,里面mRemote指向BinderProxy对象。


      如图:第四步

       ~/Android/frameworks/base/services/java/com/android/server/am

       ----ActivityManagerService.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public final class ActivityManagerService extends ActivityManagerNative{  
  2.   
  3.     public final void attachApplication(IApplicationThread thread) {  
  4.         synchronized (this) {  
  5.             int callingPid = Binder.getCallingPid();  
  6.             final long origId = Binder.clearCallingIdentity();  
  7.             attachApplicationLocked(thread, callingPid);  
  8.             Binder.restoreCallingIdentity(origId);  
  9.         }  
  10.     }  
  11.     .....  
  12. }  

      主要做以下几件事:

    (1)前面得到的ProcessRecord对象app就是用来描述MainActivity进程的,现在既然MainActivity进程已经启动起来了,那么就继续对ProcessRecord对象app进行初始化,其中最重要的是将它的成员变量thread设置为指向ApplicationThread代理对象。

       如下图:

         代码如下:

        ~/Android/frameworks/base/services/java/com/android/server/am

        ----ActivityManagerService.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public final class ActivityManagerService extends ActivityManagerNative{  
  2.      private final boolean attachApplicationLocked(IApplicationThread thread,  
  3.             int pid) {  
  4.   
  5.         /..  
  6.         ProcessRecord app;  
  7.         if (pid != MY_PID && pid >= 0) {  
  8.             synchronized (mPidsSelfLocked) {  
  9.                 app = mPidsSelfLocked.get(pid);  
  10.             }  
  11.         } else if (mStartingProcesses.size() > 0) {  
  12.             .....  
  13.         } else {  
  14.             ....  
  15.         }  
  16.   
  17.         .....  
  18.   
  19.         .....  
  20.           
  21.         app.thread = thread;  
  22.         .....  
  23. }  


      (2)r.app = app

         代码如下:

        ~/Android/frameworks/base/services/java/com/android/server/am

         ----ActivityStack.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. final boolean realStartActivityLocked(ActivityRecord r,  
  2.             ProcessRecord app, boolean andResume, boolean checkConfig)  
  3.             throws RemoteException {  
  4.   
  5.         .....  
  6.         r.app = app;  
  7.         .....  
  8. }  
   
        (3)ActivityServiceManager进程向MainActivity子线程发送

        ~/Android/frameworks/base/services/java/com/android/server/am

         ----ActivityStack.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. final boolean realStartActivityLocked(ActivityRecord r,  
  2.             ProcessRecord app, boolean andResume, boolean checkConfig)  
  3.             throws RemoteException {  
  4.   
  5.         .....  
  6.          app.thread.scheduleLaunchActivity(new Intent(r.intent), r,  
  7.                     System.identityHashCode(r),  
  8.                     r.info, r.icicle, results, newIntents, !andResume,  
  9.                     mService.isNextTransitionForward());  
  10.         .....  
  11. }  

5、ActivityServiceManager进程向MainActivity子线程发送SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION



      如图:第一步    

      ~/Android/frameworks/base/core/java/android/app

      ----ApplicationThreadNative.java,ApplicationThreadProxy类

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,  
  2.             ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,  
  3.             List<Intent> pendingNewIntents, boolean notResumed, boolean isForward)  
  4.             throws RemoteException {  
  5.         Parcel data = Parcel.obtain();  
  6.         data.writeInterfaceToken(IApplicationThread.descriptor);  
  7.         intent.writeToParcel(data, 0);  
  8.         data.writeStrongBinder(token);  
  9.         data.writeInt(ident);  
  10.         info.writeToParcel(data, 0);  
  11.         data.writeBundle(state);  
  12.         data.writeTypedList(pendingResults);  
  13.         data.writeTypedList(pendingNewIntents);  
  14.         data.writeInt(notResumed ? 1 : 0);  
  15.         data.writeInt(isForward ? 1 : 0);  
  16.         mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,  
  17.                 IBinder.FLAG_ONEWAY);  
  18.         data.recycle();  
  19.     }  
       其中token是ActivityServiceManager进程的ActivityRecord对象,用来表述MainActivity组件。

       如图:第二步, 省略binder_transaction传输过程,因为上面已经分析过了。


       如图:第三步

      ~/Android/frameworks/base/core/java/android/app

      ----ApplicationThreadNative.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public abstract class ApplicationThreadNative extends Binder  
  2.         implements IApplicationThread {  
  3.     ........  
  4.     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)  
  5.             throws RemoteException {  
  6.         switch (code) {  
  7.         case SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION:  
  8.         {  
  9.             data.enforceInterface(IApplicationThread.descriptor);  
  10.             Intent intent = Intent.CREATOR.createFromParcel(data);  
  11.             IBinder b = data.readStrongBinder();  
  12.             int ident = data.readInt();  
  13.             ActivityInfo info = ActivityInfo.CREATOR.createFromParcel(data);  
  14.             Bundle state = data.readBundle();  
  15.             List<ResultInfo> ri = data.createTypedArrayList(ResultInfo.CREATOR);  
  16.             List<Intent> pi = data.createTypedArrayList(Intent.CREATOR);  
  17.             boolean notResumed = data.readInt() != 0;  
  18.             boolean isForward = data.readInt() != 0;  
  19.             scheduleLaunchActivity(intent, b, ident, info, state, ri, pi,  
  20.                     notResumed, isForward);  
  21.             return true;  
  22.         }  
  23.         .....  
  24. }  
       其中b为一个BinderProxy的Binder代理对象,指向了ActivityManagerService中与MainActivity组件对应的一个AcitivityRecord对象。
     

       接下来,主要做以下几件事:

      (1)创建ActivityClientRecord对象。

       代码如下:

       ~/Android/frameworks/base/core/java/android/app

       ----ActivityThread.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,  
  2.                 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,  
  3.                 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {  
  4.             ActivityClientRecord r = new ActivityClientRecord();  
  5.             ...  
  6. }  

      (2)通过Handler发送信息给MainActivity主线程

         执行mActivity.put(r.token,r),其中r.token为一个BinderProxy的Binder代理对象,指向了ActivityManagerService中与MainActivity组件对应的一个AcitivityRecord对象。r为刚刚创建的ActivityClientRecord对象。

      (3)MainActivity组件执行onCreate操作,最后会调用MainActivity的onCreate方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值