首页 > 代码库 > Android Activity组件的启动过程

Android Activity组件的启动过程

0、总图



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


                                                                                                                                           

       如图:第一步    

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

       ----ActivityManagerNative.java

class ActivityManagerProxy implements IActivityManager
{
    
    public int startActivity(IApplicationThread caller, Intent intent,
            String resolvedType, Uri[] grantedUriPermissions, int grantedMode,
            IBinder resultTo, String resultWho,
            int requestCode, boolean onlyIfNeeded,
            boolean debug) throws RemoteException {
        Parcel data = http://www.mamicode.com/Parcel.obtain();>      其中caller为:

final ApplicationThread mAppThread = new ApplicationThread();
      继承于ApplicationThreadNative,ApplicationThreadNative继承于Binder实现了IApplicationThread。

      resultTo如下图所示:

 

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

        ~/Android/frameworks/base/core/jni

        ----android_util_Binder.cpp

static void android_os_Parcel_writeStrongBinder(JNIEnv* env, jobject clazz, jobject object)//clazz为Parcel,object指向了在Java层中创建的硬件访问服务FregService
{
    Parcel* parcel = parcelForJavaObject(env, clazz);//获取java层Parcel对象data的引用
    if (parcel != NULL) {
        const status_t err = parcel->writeStrongBinder(ibinderForJavaObject(env, object));
        if (err != NO_ERROR) {
            jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
        }
    }
}

       ibinderForjavaObject实现如下:

       ~/Android/frameworks/base/core/jni

       ----android_util_Binder.cpp

sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
{
    if (obj == NULL) return NULL;

    if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
        JavaBBinderHolder* jbh = (JavaBBinderHolder*)
            env->GetIntField(obj, gBinderOffsets.mObject);//这里把obj对象的mObject成员变量强制转为JavaBBinderHolder对象
        return jbh != NULL ? jbh->get(env) : NULL;
    }

    if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
        return (IBinder*)
            env->GetIntField(obj, gBinderProxyOffsets.mObject);
    }

    LOGW("ibinderForJavaObject: %p is not a Binder object", obj);
    return NULL;
}

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

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

     

       writeStrongBinder实现如下:

       ~/Android/frameworks/base/libs/binder

       ----Parcel.cpp

status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
{
    return flatten_binder(ProcessState::self(), val, this);
}

status_t flatten_binder(const sp<ProcessState>& proc,
    const sp<IBinder>& binder, Parcel* out)
{
    flat_binder_object obj;
    
    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
    if (binder != NULL) {
        IBinder *local = binder->localBinder();
        if (!local) {
            BpBinder *proxy = binder->remoteBinder();
            if (proxy == NULL) {
                LOGE("null proxy");
            }
            const int32_t handle = proxy ? proxy->handle() : 0;
            obj.type = BINDER_TYPE_HANDLE;
            obj.handle = handle;
            obj.cookie = NULL;
        } else {
            obj.type = BINDER_TYPE_BINDER;
            obj.binder = local->getWeakRefs();
            obj.cookie = local;
        }
    } else {
        obj.type = BINDER_TYPE_BINDER;
        obj.binder = NULL;
        obj.cookie = NULL;
    }
    
    return finish_flatten_binder(binder, obj, out);
}

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

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

       如图:第二步     

       Binder Driver:调用binder_transaction:

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

       ----binder.c

case BINDER_TYPE_BINDER:
		case BINDER_TYPE_WEAK_BINDER: {
			struct binder_ref *ref;
			struct binder_node *node = binder_get_node(proc, fp->binder);
			if (node == NULL) {
				node = binder_new_node(proc, fp->binder, fp->cookie);
				......
			}
			.......
			ref = binder_get_ref_for_node(target_proc, node);
			if (ref == NULL) {
				return_error = BR_FAILED_REPLY;
				goto err_binder_get_ref_for_node_failed;
			}
			if (fp->type == BINDER_TYPE_BINDER)
				fp->type = BINDER_TYPE_HANDLE;
			else
				fp->type = BINDER_TYPE_WEAK_HANDLE;
			fp->handle = ref->desc;
			......
		} break;
		case BINDER_TYPE_HANDLE:
		case BINDER_TYPE_WEAK_HANDLE: {
			struct binder_ref *ref = binder_get_ref(proc, fp->handle);
			......
			if (ref->node->proc == target_proc) {
				if (fp->type == BINDER_TYPE_HANDLE)
					fp->type = BINDER_TYPE_BINDER;
				else
					fp->type = BINDER_TYPE_WEAK_BINDER;
				fp->binder = ref->node->ptr;
				fp->cookie = ref->node->cookie;
				binder_inc_node(ref->node, fp->type == BINDER_TYPE_BINDER, 0, NULL);
				if (binder_debug_mask & BINDER_DEBUG_TRANSACTION)
					printk(KERN_INFO "        ref %d desc %d -> node %d u%p\n",
					       ref->debug_id, ref->desc, ref->node->debug_id, ref->node->ptr);
			} else {
				.......
			}
		} break;
     
      (1)如果是BINDER_TYPE_BINDER,首先创建实体对象,再创建引用对象。handle为引用句柄值。

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


        如图:第三步      

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

       ----ActivityManagerNative.java

public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
    ......
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case START_ACTIVITY_TRANSACTION:
        {
            data.enforceInterface(IActivityManager.descriptor);
            IBinder b = data.readStrongBinder();
            <span style="font-size:14px;">IApplicationThread app = ApplicationThreadNative.asInterface(b);</span>
            Intent intent = Intent.CREATOR.createFromParcel(data);
            String resolvedType = data.readString();
            ......
            IBinder resultTo = data.readStrongBinder();
            ......
            return true;
        }


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

      ~/Android/frameworks/base/core/jni

      ----android_util_Binder.cpp

static jobject android_os_Parcel_readStrongBinder(JNIEnv* env, jobject clazz)
{
    Parcel* parcel = parcelForJavaObject(env, clazz);//获得Java层reply的引用
    if (parcel != NULL) {
        return javaObjectForIBinder(env, parcel->readStrongBinder());
    }
    return NULL;
}

      ~/Android/frameworks/base/libs/binder

      ----Parcel.cpp

sp<IBinder> Parcel::readStrongBinder() const
{
    sp<IBinder> val;
    unflatten_binder(ProcessState::self(), *this, &val);
    return val;
}

status_t unflatten_binder(const sp<ProcessState>& proc,
    const Parcel& in, sp<IBinder>* out)
{
    const flat_binder_object* flat = in.readObject(false);
    
    if (flat) {
        switch (flat->type) {
            case BINDER_TYPE_BINDER:
                *out = static_cast<IBinder*>(flat->cookie);
                return finish_unflatten_binder(NULL, *flat, in);
            case BINDER_TYPE_HANDLE:
                *out = proc->getStrongProxyForHandle(flat->handle);
                return finish_unflatten_binder(
                    static_cast<BpBinder*>(out->get()), *flat, in);
        }        
    }
    return BAD_TYPE;
}


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

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


       然后执行javaObjectForIBinder。

       ~/Android/frameworks/base/core/jni

       ----android_util_Binder.cpp

jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
{
    if (val == NULL) return NULL;

    if (val->checkSubclass(&gBinderOffsets)) {
        // One of our own!
        jobject object = static_cast<JavaBBinder*>(val.get())->object();
        ........
        return object;
    }

    // For the rest of the function we will hold this lock, to serialize
    // looking/creation of Java proxies for native Binder proxies.
    AutoMutex _l(mProxyLock);

    // Someone else's...  do we know about it?
    jobject object = (jobject)val->findObject(&gBinderProxyOffsets);//检查当前进程之前是否已经为它创建过一个BinderProxy对象
    if (object != NULL) {//如果有返回来的就是一个指向该BinderProxy对象的WeakReference对象object,即一个弱引用对象
        jobject res = env->CallObjectMethod(object, gWeakReferenceOffsets.mGet);//由于弱引用对象object所指向的BinderProxy对象可能已经失效,因此,需要检查它的有效性,方法是调用它的成员函数get来获得一个强引用对象。
        if (res != NULL) {//如果不为NULL
            ......
            return res;//直接返回
        }
        .....
        android_atomic_dec(&gNumProxyRefs);//如果为NULL
        val->detachObject(&gBinderProxyOffsets);//解除它与一个无效的BinderProxy对象的对应关系
        env->DeleteGlobalRef(object);//删除弱引用对象的全局引用
    }

    object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);//创建一个BinderProxy对象
    if (object != NULL) {
        .......
        env->SetIntField(object, gBinderProxyOffsets.mObject, (int)val.get());//BinderProxy.mObject成员变量记录了这个BpBinder对象的地址
        val->incStrong(object);

        // The native object needs to hold a weak reference back to the
        // proxy, so we can retrieve the same proxy if it is still active.
        jobject refObject = env->NewGlobalRef(
                env->GetObjectField(object, gBinderProxyOffsets.mSelf));//获取BinderProxy内部的成员变量mSelf(BinderProxy的弱引用对象),接着再创建一个全局引用对象来引用它
        val->attachObject(&gBinderProxyOffsets, refObject,
                jnienv_to_javavm(env), proxy_cleanup);//把它放到BpBinder里面去,下次就要使用时,就可以在上一步调用BpBinder::findObj把它找回来了

        // Note that a new object reference has been created.
        android_atomic_inc(&gNumProxyRefs);
        incRefsCreated(env);
    }

    return object;
}

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

IBinder resultTo = data.readStrongBinder();

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

            IBinder b = data.readStrongBinder();
            IApplicationThread app = ApplicationThreadNative.asInterface(b);
        然后生成ActivityManagerProxy对象,里面mRemote指向BinderProxy对象。

       

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

        ----ActivityManagerService.java

public final class ActivityManagerService extends ActivityManagerNative{

    public final int startActivity(IApplicationThread caller,
            Intent intent, String resolvedType, Uri[] grantedUriPermissions,
            int grantedMode, IBinder resultTo,
            String resultWho, int requestCode, boolean onlyIfNeeded,
            boolean debug) {
        return mMainStack.startActivityMayWait(caller, intent, resolvedType,
                grantedUriPermissions, grantedMode, resultTo, resultWho,
                requestCode, onlyIfNeeded, debug, null, null);
    }
    .....
}


         主要干了以下几件事:

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

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

       ----ActivityStack.java,final int startActivityLocked

ActivityRecord sourceRecord = null;
        if (resultTo != null) {
            int index = indexOfTokenLocked(resultTo);
            .........
            if (index >= 0) {
                sourceRecord = (ActivityRecord)mHistory.get(index);
                ........
            }
        }
     (2)根据传递过来的intent创建了一个新的ActivityRecord对象,用来描述即将启动的Activity组件,即MainActivity组件。代码如下:

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

       ----ActivityStack.java,final int startActivityLocked

ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
                intent, resolvedType, aInfo, mService.mConfiguration,
                resultRecord, resultWho, requestCode, componentSpecified);
     (3)由于需要在新的任务栈中启动Activity,所以设置r.task属性。代码如下:

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

       ----ActivityStack.java,startActivityUncheckedLocked

if (r.resultTo == null && !addingToTask
                && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
            // todo: should do better management of integers.
            ......
            r.task = new TaskRecord(mService.mCurTask, r.info, intent,
                    (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
            ......
            newTask = true;
            if (mMainStack) {
                mService.addRecentTaskLocked(r.task);
            }
            
        } 

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

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

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

final int NH = mHistory.size();

        int addPos = -1;
        
        .......
        if (addPos < 0) {
            addPos = NH;
        }
        
        .......
        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

if (prev.app != null && prev.app.thread != null) {
            ........
            try {
                .......
                prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
                        prev.configChangeFlags);
                .......
            } catch (Exception e) {
                .......
            }
        }


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



      如图:第一步    

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

      ----ApplicationThreadNative.java,ApplicationThreadProxy类

public final void schedulePauseActivity(IBinder token, boolean finished,
            boolean userLeaving, int configChanges) throws RemoteException {
        Parcel data = http://www.mamicode.com/Parcel.obtain();>       其中token是ActivityServiceManager进程的ActivityRecord对象,用来表述Lancher组件。

   

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


       如图:第三步

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

      ----ApplicationThreadNative.java

public abstract class ApplicationThreadNative extends Binder
        implements IApplicationThread {
    ........
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION:
        {
            data.enforceInterface(IApplicationThread.descriptor);
            IBinder b = data.readStrongBinder();
            boolean finished = data.readInt() != 0;
            boolean userLeaving = data.readInt() != 0;
            int configChanges = data.readInt();
            schedulePauseActivity(b, finished, userLeaving, configChanges);
            return true;
        }
      其中b为一个BinderProxy的Binder代理对象,指向了ActivityManagerService中与Laucher组件对应的一个AcitivityRecord对象。


       如图:第四步

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

      ----ActivityThread.java

private final class ApplicationThread extends ApplicationThreadNative {
        .......

        public final void schedulePauseActivity(IBinder token, boolean finished,
                boolean userLeaving, int configChanges) {
            queueOrSendMessage(
                    finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
                    token,
                    (userLeaving ? 1 : 0),
                    configChanges);
        }
       向Laucher主线程发送PAUSE_ACTIVITY_FINISHING命令。

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

      ----ActivityThread.java

 private final class H extends Handler {
        .........
        public void handleMessage(Message msg) {
            .......
            switch (msg.what) {
                ........
                case PAUSE_ACTIVITY:
                    handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
                    .......
                    break;
      (1)获取了ActivityClientRecord对象,在Lancher进程启动的每一个Activity组件都使用一个ActivityClientRecord对象来描述。

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

         代码如下:

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

      ----ActivityThread.java

private final void handlePauseActivity(IBinder token, boolean finished,
            boolean userLeaving, int configChanges) {
        ActivityClientRecord r = mActivities.get(token);
        if (r != null) {
            //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
            if (userLeaving) {
                performUserLeavingActivity(r);
            }

            r.activity.mConfigChangeFlags |= configChanges;
            Bundle state = performPauseActivity(token, finished, true);

            // Make sure any pending writes are now committed.
            QueuedWork.waitToFinish();
            
            // Tell the activity manager we have paused.
            try {
                ActivityManagerNative.getDefault().activityPaused(token, state);
            } catch (RemoteException ex) {
            }
        }
    }

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


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



       如图:第一步

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

       ----ActivityManagerNative.java

public void activityPaused(IBinder token, Bundle state) throws RemoteException
    {
        Parcel data = http://www.mamicode.com/Parcel.obtain();>        token为一个BinderProxy的Binder代理对象,指向了ActivityManagerService中与Laucher组件对应的一个AcitivityRecord对象。

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


       如图:第三步

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

       ----ActivityManagerNative.java

public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
    ......
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case ACTIVITY_PAUSED_TRANSACTION: {
            data.enforceInterface(IActivityManager.descriptor);
            IBinder token = data.readStrongBinder();
            Bundle map = data.readBundle();
            activityPaused(token, map);
            reply.writeNoException();
            return true;
        }
    .......
}
        其中token是ActivityServiceManager进程的ActivityRecord对象,用来表述Lancher组件。


        如图:第四步

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

        ----ActivityManagerService.java

public final class ActivityManagerService extends ActivityManagerNative{

    public final void activityPaused(IBinder token, Bundle icicle) {
        // Refuse possible leaked file descriptors
        if (icicle != null && icicle.hasFileDescriptors()) {
            throw new IllegalArgumentException("File descriptors passed in Bundle");
        }

        final long origId = Binder.clearCallingIdentity();
        mMainStack.activityPaused(token, icicle, false);
        Binder.restoreCallingIdentity(origId);
    }
    .....
}

      主要做了以下几件事:

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

       代码如下:

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

        ----ActivityManagerService.java

final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
        ProcessRecord app = getProcessRecordLocked(processName, info.uid);
        .......
        if (app == null) {
            app = newProcessRecordLocked(null, info, processName);
            .......
        } else {
            ......
        }
        ......
    }

     (2)开启MainActivity子线程。      

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

       ----ActivityManagerService.java,startProcessLocked

int pid = Process.start("android.app.ActivityThread",
                    mSimpleProcessManagement ? app.processName : null, uid, uid,
                    gids, debugFlags, null);

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

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

      ----ActivityThread.java

 public static final void main(String[] args) {
        .....

        Looper.prepareMainLooper();
        ......
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        ......

        Looper.loop();

        ......
    }

private final void attach(boolean system) {
        .....
        mSystemThread = system;
        if (!system) {
            ......
            IActivityManager mgr = ActivityManagerNative.getDefault();
            try {
                mgr.attachApplication(mAppThread);
            } catch (RemoteException ex) {
            }
        } 
        .....
}



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



        如图:第一步

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

       ----ActivityManagerNative.java

class ActivityManagerProxy implements IActivityManager
{
    
   public void attachApplication(IApplicationThread app) throws RemoteException
    {
        Parcel data = http://www.mamicode.com/Parcel.obtain();>      app为:

final ApplicationThread mAppThread = new ApplicationThread();
      继承于ApplicationThreadNative,ApplicationThreadNative继承于Binder实现了IApplicationThread。

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


       如图:第三步

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

       ----ActivityManagerNative.java

public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
    ......
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case ATTACH_APPLICATION_TRANSACTION: {
            data.enforceInterface(IActivityManager.descriptor);
            IApplicationThread app = ApplicationThreadNative.asInterface(
                    data.readStrongBinder());
            if (app != null) {
                attachApplication(app);
            }
            reply.writeNoException();
            return true;
        }
    .......
}
      首先生成BinderProxy对象,里面的mObject指向代理对象,向上转型为IBinder。
      然后生成ActivityManagerProxy对象,里面mRemote指向BinderProxy对象。


      如图:第四步

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

       ----ActivityManagerService.java

public final class ActivityManagerService extends ActivityManagerNative{

    public final void attachApplication(IApplicationThread thread) {
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid);
            Binder.restoreCallingIdentity(origId);
        }
    }
    .....
}

      主要做以下几件事:

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

       如下图:

         代码如下:

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

        ----ActivityManagerService.java

public final class ActivityManagerService extends ActivityManagerNative{
     private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid) {

        /..
        ProcessRecord app;
        if (pid != MY_PID && pid >= 0) {
            synchronized (mPidsSelfLocked) {
                app = mPidsSelfLocked.get(pid);
            }
        } else if (mStartingProcesses.size() > 0) {
            .....
        } else {
            ....
        }

        .....

        .....
        
        app.thread = thread;
        .....
}


      (2)r.app = app

         代码如下:

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

         ----ActivityStack.java

final boolean realStartActivityLocked(ActivityRecord r,
            ProcessRecord app, boolean andResume, boolean checkConfig)
            throws RemoteException {

        .....
        r.app = app;
        .....
}
   
       (3)ActivityServiceManager进程向MainActivity子线程发送

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

         ----ActivityStack.java

final boolean realStartActivityLocked(ActivityRecord r,
            ProcessRecord app, boolean andResume, boolean checkConfig)
            throws RemoteException {

        .....
         app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
                    System.identityHashCode(r),
                    r.info, r.icicle, results, newIntents, !andResume,
                    mService.isNextTransitionForward());
        .....
}

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



      如图:第一步    

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

      ----ApplicationThreadNative.java,ApplicationThreadProxy类

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
            ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
    		List<Intent> pendingNewIntents, boolean notResumed, boolean isForward)
    		throws RemoteException {
        Parcel data = http://www.mamicode.com/Parcel.obtain();>       其中token是ActivityServiceManager进程的ActivityRecord对象,用来表述MainActivity组件。

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


       如图:第三步

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

      ----ApplicationThreadNative.java

public abstract class ApplicationThreadNative extends Binder
        implements IApplicationThread {
    ........
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION:
        {
            data.enforceInterface(IApplicationThread.descriptor);
            Intent intent = Intent.CREATOR.createFromParcel(data);
            IBinder b = data.readStrongBinder();
            int ident = data.readInt();
            ActivityInfo info = ActivityInfo.CREATOR.createFromParcel(data);
            Bundle state = data.readBundle();
            List<ResultInfo> ri = data.createTypedArrayList(ResultInfo.CREATOR);
            List<Intent> pi = data.createTypedArrayList(Intent.CREATOR);
            boolean notResumed = data.readInt() != 0;
            boolean isForward = data.readInt() != 0;
            scheduleLaunchActivity(intent, b, ident, info, state, ri, pi,
                    notResumed, isForward);
            return true;
        }
        .....
}
       其中b为一个BinderProxy的Binder代理对象,指向了ActivityManagerService中与MainActivity组件对应的一个AcitivityRecord对象。
     

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

      (1)创建ActivityClientRecord对象。

       代码如下:

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

       ----ActivityThread.java

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
                List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
            ActivityClientRecord r = new ActivityClientRecord();
            ...
}

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

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

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