Android Activity 的启动流程

一、背景

1.1、本来是想先了解一下context 的,源代码看下去就先了解了Activity的启动流程,所以就先总结一下 Activity的启动流程吧。

注意:下面所有源码基于 http://androidxref.com/ - Marshmallow - 6.0.0_r1

二、Activity 多种启动情况

  •         Launcher 启动一个全新APP中的一个Activity
  •         一个APP中 Activity A 启动 Activity B
  •         从Activity A 点击Home 回到 Launcher,再进入Activity A

三、背景知识

       3.1、 Activity 的启动是 客户端进程(CP) 和 ActivityManagerServicre (AMS) 多次交互的结果。CP和AMS进程的通讯是使用IBinder进行通讯。其中CP 可以通过 ActivityManagerProxy 给 MAS 进行消息,AMS可以通过 ApplicationThread 给 CP发送消息。

       ActivityManagerProxy(AMP) : AMS 在 每一个CP中的代理,可以通过 ActivityManagerNative.getDefault() 获取。通过AMP可以向AMS发送消息。

class ActivityManagerNative{

                static public IActivityManager getDefault() {
                      return gDefault.get();
                 }

                private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
                        protected IActivityManager create() {
                            IBinder b = ServiceManager.getService("activity");
                            if (false) {
                                Log.v("ActivityManager", "default service binder = " + b);
                            }
                            IActivityManager am = asInterface(b);
                            if (false) {
                                Log.v("ActivityManager", "default service = " + am);
                            }
                            return am;
                        }
                  };

              static public IActivityManager asInterface(IBinder obj) {
                    if (obj == null) {
                        return null;
                    }
                    IActivityManager in =
                        (IActivityManager)obj.queryLocalInterface(descriptor);
                    if (in != null) {
                        return in;
                    }
                    //这里可以看到,实际上是拿到了ActivityManagerProxy(AMP),就是ACtivityManagerService在客户端的代理,通过这个AMP 就可以和AMS进行跨进程通讯
                    return new ActivityManagerProxy(obj);
                 }  

} 

       ApplicationThread:ActivityThread中的一个参数,随着ActivityThread 的创建而创建。                          

public final class ActivityThread {
  ...
  final ApplicationThread mAppThread = new ApplicationThread();
  ...
  private class ApplicationThread extends ApplicationThreadNative {
   ...
  }
}

public abstract class ActivityManagerNative extends Binder implements IActivityManager{
   ...
}

3.2、Binder 跨进程通讯 -- 后续更新博客补充

四、启动Acticity

  4.1、先贴上一个Activity 启动的整体流程图

整体流程:

  • Launcher  通知 AMS 将要启动 CP 中的Activity
  • AMS 记录将将要启动的Activity的信息,并且通知Luancher 进入onPause 状态
  • Launcher 进入 pause 状态 ,并通知到 AMS
  • AMS 启动一个新的进程作为CP进程,并在进程中创建ActivityThread 和初始化CP主线程。
  • CP传入ApplicationThread 与 AMS 进行通讯。
  • AMS 通知 ActivityThread 创建 Application ,并执行 onCreate() 方法
  • ActivityThread 创建 Application 成功之后通知AMS
  • AMS 通知 ActivityThread 创建 Activity,并把Activity 和Context、Window 进行绑定 ,最后调用Activity的 onCreate() 方法

五、源码分析

5.1、Launcher 启动CP中的Activity

   调用 startActivity(Intent) 启动新的Activity

扫描二维码关注公众号,回复: 11947119 查看本文章
class Activity{
    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
	    //所有的Activity的 start 最终都是到了 startActivityForResult()
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }
   
    //startActivity() 有多重重载的方法,但是最终都是来到 startActivityForResult 中启动Activiy
    @Override
    public void startActivityForResult(
            String who, Intent intent, int requestCode, @Nullable Bundle options) {
        Uri referrer = onProvideReferrer();
        if (referrer != null) {
            intent.putExtra(Intent.EXTRA_REFERRER, referrer);
        }
	// activity 从这里进入启动 ,跳转到  mInstrumentation.execStartActivity 中 
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, who,
                intent, requestCode, options);
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, who, requestCode,
                ar.getResultCode(), ar.getResultData());
        }
        cancelInputsAndStartExitTransition(options);
    }
}

 5.2、 上面可以看到,最终进入了 Instrumentation.execStartActivity 中,其中 Instrumentation 是可以管理 Activity 的生命周期的调用。接下来我们进入Instrumentation.execStartActivity

  public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
			
	//contextThread 这是创建Activity的主线程,外层传入的是一个 ApplicationThread
        //这里进行强转- ApplicationThread extends IApplicationThread.Stub   
        //这里的  ApplicationThread  同时也是一个Ibinder ,有理由怀疑用到了跨进程通讯。其中ActivityManagerService 就是一个跨进程的服务。
		
	//第二遍回顾:其实这就是一个跨进程通讯,每一个APP进程里边有一个ActivityThread,ActivityThread初始化的时候会创建一个 ApplicationThread对象,用于和AMS进行通讯
	//在通讯的过程中AMS通过 ApplicationThread 和ActiityThread 进行跨进程通讯
	
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        Uri referrer = target != null ? target.onProvideReferrer() : null;
        if (referrer != null) {
            intent.putExtra(Intent.EXTRA_REFERRER, referrer);
        }
        ... ... 
        try {
             ... ...
			
	       /**
		//在这里启动Activity ,核心功能都在 whoThread 中完成
		ActivityManagerNative.getDefault()  ActivityManagerService的客户端(用户进程)的代理对象,作为代理类
		这里是获取了ActivityManagerProxy,前面背景知识点说到这个(内部有关于IBinder 通讯,先不理会这个 ,粗略理解链接:https://www.jianshu.com/p/30ed35c06bba)
		然后调用 ActivityManagerNative.startActivity() 方法.
		看看这里边发生了什么?*/

            int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
		//检查 Activity 一些异常情况,比如Activity 是否在Manifest中注册就是这里检查的,里边会爆出各种错误			
            checkStartActivityResultcheckStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    } 

5.3 、 进入ActivityManagerProxy 看看 startActivity()

public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
		//对数据进行了 封装,要开始AIDl传输数据了	
        Parcel data = Parcel.obtain();  //需要传输的结构体
        Parcel reply = Parcel.obtain(); //回馈的数据结构体
        ... ....  //写入数据 
	/*
	mRemote 这是一个代理
	class ActivityManagerProxy implements IActivityManager
        {
		public ActivityManagerProxy(IBinder remote)
		{
		  mRemote = remote;
		}
	}
	很明显,这个东西就是一个代理。实际上这是 ActivityManagerService(AMS)在远程客户端的一个代理
	*/
        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);   // 给 AMS 发送数据,这时候AMS要干嘛?
        reply.readException();  
	//这里已经是AMS 启动完了启动完了Activity 返回了结果。那么这里可以判断到在AMS中启动这个这个ACtivity ,该去看看AMS了。
	//这里是IBinder的机制,所以我们需要去查看 AMS.onTransact() 方法,东西在里边。怎么调用到 onTransact 可以去看看 Binder.cpp 源码
        int result = reply.readInt(); 
        reply.recycle();
        data.recycle();
        return result;
    }   

5.4、AMS 在 onTransact() 中收到消息,记录信息,并通知 launcher 进入 pause 

//AMS 集成了 ActivityManagerNative,下面称为: AMN,上面可以知道,AMN 集成了 IActivityManager  
class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback

AMS收到数据之后记录了即将启动的Activity 的信息,并进行了一些系列的异常判断和参数解析操作,最后通知当前的Activity 进入 pause 状态  

AMS.onTransact() -->  AMS.startActivity  --> AMS.startActivityAsUser  -->  ActivityStackSupervisor.startActivityMayWait--> ActivityStackSupervisor.startActivityLocked --> ActivityStackSupervisor.startActivityUncheckedLocked-->ActivityStack.startActivityLocked --> ActivityStack.resumeTopActivityLocked --> ActivityStackSupervisor.resumeTopActivitiesLocked -->  ActivityStack.resumeTopActivityLocked

class ActivityStackSupervisor{
    

   final int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, Intent intent, String resolvedType,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int startFlags,
            ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,
            Bundle options, boolean ignoreTargetSecurity, int userId,
            IActivityContainer iContainer, TaskRecord inTask) {
   
        ... ...
 
        // Collect information about the target of the Intent.
		//解析Activity 获得其中数据,如果发现有多个Activiy 可以选择,弹出弹框让用户选择
        ActivityInfo aInfo =resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);

         ... ...
			
		//上面异常检查和信息获取完成之后,到达这里终于又看到熟悉的startActivity 了
          int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                    voiceSession, voiceInteractor, resultTo, resultWho,
                    requestCode, callingPid, callingUid, callingPackage,
                    realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity,componentSpecified, null, container, inTask);

        ... ...

            return res;
        }
    }




   final int startActivityLocked(IApplicationThread caller,
            Intent intent, String resolvedType, ActivityInfo aInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode,
            int callingPid, int callingUid, String callingPackage,
            int realCallingPid, int realCallingUid, int startFlags, Bundle options,
            boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container, TaskRecord inTask) {
        ... ...
		//以上全部都是检查错误,没有异常情况,那么进入下一步 
        err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, true, options, inTask);
        ... ... 
        return err;
    }
   


   /*
    这个方法超级长,给看吐了 
   */
   final int startActivityUncheckedLocked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
            boolean doResume, Bundle options, TaskRecord inTask) {
        final Intent intent = r.intent;
        final int callingUid = r.launchedFromUid;

        // In some flows in to this function, we retrieve the task record and hold on to it
        // without a lock before calling back in to here...  so the task at this point may
        // not actually be in recents.  Check for that, and if it isn't in recents just
        // consider it invalid.
        if (inTask != null && !inTask.inRecents) {
            Slog.w(TAG, "Starting activity in task not in recents: " + inTask);
            inTask = null;
        }

		//这里有点熟悉了,我们常用的集中Activity的启动方式 ---下面很多都是模式选择判断和栈情况的判断
        final boolean launchSingleTop = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP;
        final boolean launchSingleInstance = r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE;
        final boolean launchSingleTask = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK;
        ... ... 
        
		//前面的代码看的有点晕乎,感觉就是判断好Activity的启动模式,还有Activity的stack 异常情况判断
		//下面重点看一下---- 
		
        ActivityStack.logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
        targetStack.mLastPausedActivity = null;
		//进入这里看看吧 ?
        targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
        if (!launchTaskBehind) {
            // Don't set focus on an activity that's going to the back.
            mService.setFocusedActivityLocked(r, "startedActivity");
        }
        return ActivityManager.START_SUCCESS;
    }




    boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
            Bundle targetOptions) {
        if (targetStack == null) {
            targetStack = mFocusedStack;
        }
        // Do targetStack first.
        boolean result = false;
        if (isFrontStack(targetStack)) {
			//如果带启动的Activity所在的Task 是前台Task ,调用 ActivityStack 的 resumeTopActivityLocked
            result = targetStack.resumeTopActivityLocked(target, targetOptions);
        }


        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
                final ActivityStack stack = stacks.get(stackNdx);
                if (stack == targetStack) {
                    // Already started above.
                    continue;
                }
                if (isFrontStack(stack)) {
					//找到所有当前栈的Task,调动起 resumeTopActivityLocked 
                    stack.resumeTopActivityLocked(null);
                }
            }
        }
        return result;
    }
  

}

进入 ActivityStack ,要启动新的Activity ,必须先把 Launcher 中当前的Activity 进入 pause 

class ActivityStack{

     final boolean resumeTopActivityLocked(ActivityRecord prev) {
        return resumeTopActivityLocked(prev, null);
    }

    final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
        ... ...
         result = resumeTopActivityInnerLocked(prev, options);
       ...
    }
    
   private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
        ... ...
		//获取父Activity 
        ActivityRecord parent = mActivityContainer.mParentActivity;  
        ... ...
        final ActivityRecord next = topRunningActivityLocked(null); //下一个即将要启动的Activity记录
        ... ...
		/*
           现在好去启动下一个 Activity ,先要 pause 当前的Activity 		
		*/
        ... .... 	
        boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
        if (mResumedActivity != null) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing " + mResumedActivity);					
			//这里把顶部Activity 进入 pause  		
            pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
        }
        ... ...
        ActivityStack lastStack = mStackSupervisor.getLastStack();
        if (next.app != null && next.app.thread != null) {		
			///下面的情况类似于启动 网易云app 成功之后,点击Home 回到Luancher 界面,在进入网易
            // 判断条件可以看到,下一个需要启动的Actiity 的记录和 thread 都已经创建了
			
            // This activity is now becoming visible.  // 需要启动Activity可见
            mWindowManager.setAppVisibility(next.appToken, true);
            ... ...
            try {
               ... ...
                if (next.newIntents != null) {
					//如果这个  Activity 的 Intent 不等于空
					//调用activity 所在进程的 ApplicationThread 中的 scheduleNewIntent ,在这里边会调用 activity 的 newIntent
                    next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
                }
                ... ... 
				//调用activity 所在进程的 ApplicationThread 中的 scheduleResumeActivity, 会进入Activity 的 resume
                next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState, mService.isNextTransitionForward(), resumeAnimOptions);
mStackSupervisor.checkReadyForSleepLocked();
            } catch (Exception e) {
                // Whoops, need to restart this activity!
                ... ...
                return true;
            } 
        } else {
           ... ...
			//这里开始创建Activity 所在的进程,或者APP 已经启动了,这里启动新的Activity 
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }
        return true;
    }


    // 看看是如何通知Luancher 中的Activity 进入pause 状态的  
  
     final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming, boolean dontWait) {
        if (mPausingActivity != null) {
            
        ActivityRecord prev = mResumedActivity; //获取当前的Actiity 的记录 
        ... ...
        if (prev.app != null && prev.app.thread != null) {           
            try {              
				//调用当前Activity 的 ApplicationThread 中的 schedulePauseActivity ,通知其进入 pause 状态, Activity 进入 pause 之后,会在 prev中回馈进入结果
                prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                        userLeaving, prev.configChangeFlags, dontWait);
            } catch (Exception e) {
               ... ...
            }
        } 

    }

}

其中在  ActivityStack.resumeTopActivityLocked 中会通知Luancher 进入pause ,进入pause 之通过ActivityRcord 判断 CP进程和CP Activity 是否已经创建。

  如果创建了,调用  CP Activity 的 resume 方法,否者进入再去创建新的进程.,流程图如下:

5.5、AMS 创建 CP 进程 ,并在进程中创建ActivityThread 和初始化CP主线程

class ActivityStackSupervisor{
     
    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
         ... ...
        if (app != null && app.thread != null) {
            try {
                
				//目标ApplicationThread 已经启动,启动 Activity
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "+ r.intent.getComponent().flattenToShortString(), e);
            }
        }
		//进程不存在,启动应用进程
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);
    }
}

 在 ActivityStackSupervisor 中启动 ,对进程CP 进程进行判断,如果CP 进程以及启动,那么直接调用 realStartActivityLocked ,都在进入 AMS 中创建新的进程。这里我们仅分析新进程的分支 ,后续会回来分析 realStartActivityLocked 

class ActivityManagerService{
   
   private final void startProcessLocked(ProcessRecord app, String hostingType,
            String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
        			/**
			这里启动一个进程
		    在 Process 中通过反射建立一个新的进程,并且通过反射调用 ActivityThread 中的 main 方法 
			启动ActivityThread 之后,使用socket 给 ActivityThread 发送相关参数
			**/
            boolean isActivityProcess = (entryPoint == null);
            if (entryPoint == null) entryPoint = "android.app.ActivityThread";
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
                    app.processName);
            checkTime(startTime, "startProcess: asking zygote to start proc");
            Process.ProcessStartResult startResult = Process.start(entryPoint,
                    app.processName, uid, uid, gids, debugFlags, mountExternal,
                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
                    app.info.dataDir, entryPointArgs);					
            checkTime(startTime, "startProcess: returned from zygote!");
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

  }

}

可以看到,在AMS的 startProcessLocked 中,创建一个新的进程 Process ,在其内部,使用反射调用 ActivityThread 的main 方法。

class ActivityThread{

    final ApplicationThread mAppThread = new ApplicationThread();

    public static void main(String[] args) {
         ... ...
        //创建 Looper
        Looper.prepareMainLooper();
		
		//创建ActivityThread 
        ActivityThread thread = new ActivityThread();
		//ActivityThread 绑定到 AMS, 如此应用进程和和AMS 绑定在一块了,见13.2
        thread.attach(false);

        if (sMainThreadHandler == null) {
			//进程对应的主线程Handler
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();
    }

}

在main 函数中,初始化主线程,并且创建 ActivityThread ,其中 ApplicationThread 作为 ActivityThread 的遍历跟着创建。这里就保证了一个进程里边只有一个 ActivityThread 和 ApplicationThread 。

5.6、CP传入ApplicationThread 与 AMS 进行通讯。

上面 ActivityThread 中可以看到,main函数中调用了ActivityThread.attach(false) 。这里把 ApplicationThread 和 传递给AMS,实现AMS和 ActivityThread 的通讯。

class ActivityThread{
    private void attach(boolean system) {
    //获得AMS的代理对象
    final IActivityManager mgr = ActivityManagerNative.getDefault();  
    try {
	      //通过AMP 把 MAS 和 ApplicationThread 进行绑定 ,实际上调用了 AMS 中的         attachApplication
          mgr.attachApplication(mAppThread);
     } catch (RemoteException ex) {
       // Ignore
    }
}
}


5.7、AMS 通知 ActivityThread 创建 Application ,并执行 onCreate() 方法

通过上面的 attach ,AMS 拿到 ApplicationThread 可以了ActivityThread 进行通讯。

class  ActivityManagerService{
    private final boolean attachApplicationLocked(IApplicationThread thread,int pid) {
		//获取进程记录
        ProcessRecord app;
        if (pid != MY_PID && pid >= 0) {
            synchronized (mPidsSelfLocked) {
                app = mPidsSelfLocked.get(pid);
            }
        } else {
            app = null;
        }

		//如果 AMS 中没有记录,杀死进程(进程是由于锁定AMS中启动的,所以一定有记录,没有记录认为该进程可以去除)
        if (app == null) {          
            if (pid > 0 && pid != MY_PID) {
				//杀死进程
                Process.killProcessQuiet(pid);
            } else {
                try {
                    thread.scheduleExit();
                } catch (Exception e) {
                    // Ignore exceptions.
                }
            }
            return false;
        }

        if (app.thread != null) {
			/**
			如果获取的记录中ApplicationThread 不为null ,需要处理掉这个 ApplicationThread
			pid 是有可能复用的,有可能是旧的进程刚刚释放,新的进程又使用了这个pid ,导致出现 ApplicationThread 没有被清空的情况下,又进来了新的进程使用了这个pid
			**/
            handleAppDiedLocked(app, true, true);
        }

        final String processName = app.processName;
        try {
			//创建 APP 死亡代理,app 被 kill 之后可以通知 AMS
            AppDeathRecipient adr = new AppDeathRecipient(
                    app, pid, thread);
            thread.asBinder().linkToDeath(adr, 0);
            app.deathRecipient = adr;
        } catch (RemoteException e) {
          ...
        }
        ... ...   
        try {           
			... ...		
			//绑定Application,并调用Application的onCreate 方法
            thread.bindApplication(processName, appInfo, providers,app.instrumentationClass,profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,isRestrictedBackupMode || !normalMode, app.persistent,new Configuration(mConfiguration), app.compat,getCommonServicesLocked(app.isolated),mCoreSettingsObserver.getCoreSettingsLocked());
					
            updateLruProcessLocked(app, false, null);
            app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
        } catch (Exception e) {
           ... ... 
        }
        if (normalMode) {
            try {
				//进程启动完成了,Application绑定 Instrumentation 成功了,启动主 Activiy
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
        }
        ... ...
        return true;

    }

}

上面可以看到,ActivityThread 调用 attach 其实是把 ApplicationThread 传递到 AMS,多方便 AMS 与ActivityThread 通讯。

其中 

thread.bindApplication(processName, appInfo, providers,app.instrumentationClass,profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,isRestrictedBackupMode || !normalMode, app.persistent,new Configuration(mConfiguration), app.compat,getCommonServicesLocked(app.isolated),mCoreSettingsObserver.getCoreSettingsLocked());

会回调到 ActivityThread 的 handleBindApplication中,通知 ActivityThread 启动创建新的Application,并调用其中onCreate方法。

class ActivityThread{
     
       private void handleBindApplication(AppBindData data) {
             ... ...
            //创建 ContextImpl 实例
            final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
             ... ...

            if (data.instrumentationName != null) {
		
            //创建 Instrumentation
            try {
				//创建一个新的 Instrumentation ,使用 classLoader 的 newInstance 的方式创建
                java.lang.ClassLoader cl = instrContext.getClassLoader();
                mInstrumentation = (Instrumentation)
                    cl.loadClass(data.instrumentationName.getClassName()).newInstance();
            } catch (Exception e) {
               ... ...
            }

			//在 Instrumentation 调用init 把 Application 赋值给 Instrumentation
            mInstrumentation.init(this, instrContext, appContext,
                   new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher,
                   data.instrumentationUiAutomationConnection);
        } else {
			//新建一个新的 Instrumentation
            mInstrumentation = new Instrumentation();
        }

        try {
			/*创建Application
               LoadedApk.makeApplication() -> mInstrumentation.newApplication() 
               static public Application newApplication(Class<?> clazz, Context context)
                throws InstantiationException, IllegalAccessException, 
                ClassNotFoundException {
				    //把ContextImpl 和Application 进行绑定 
				    Application app = (Application)clazz.newInstance();
				    app.attach(context);
				    return app;
			    }			  
			**/
            Application app = data.info.makeApplication(data.restrictedBackupMode, null);
            mInitialApplication = app;
            ... ...
            try {
				//调用application 的 onCreate 方法 
				/**
    				 public void callApplicationOnCreate(Application app) {
					    app.onCreate();
				     }
				*/
                mInstrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                ... ... 
            }
        } finally {
            ...
        }

     }

}

5.8、AMS 通知 ActivityThread 创建 Activity,并把Activity 和Context、Window 进行绑定 ,最后调用Activity的 onCreate() 方法

上面AMS 可以看到 AMS 通知创建了 Application 之后,进入

mStackSupervisor.attachApplicationLocked(app)
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
        ... ...   
                        try {
							//这就回到了之前说明的,如果应用进程以及创建,那么调用 realStartActivityLocked
                            if (realStartActivityLocked(hr, app, true, true)) {
                                didSomething = true;
                            }
                        } catch (RemoteException e) {
                            Slog.w(TAG, "Exception in new application when starting activity "
                                  + hr.intent.getComponent().flattenToShortString(), e);
                            throw e;
                        }
      ...
}

可以看到,最终还是回到了  realStartActivityLocked

final boolean realStartActivityLocked(ActivityRecord r,
            ProcessRecord app, boolean andResume, boolean checkConfig)
            throws RemoteException {
    ...
    app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage,task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
    ...

}

在 realStartActivityLocked 最终还是通过 ApplicationThread 与ActivityThread 进行通讯。告知其进入 scheduleLaunchActivity。实际上调用到了 ActivityThread.handleLaunchActivity 方法。

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {

    ... ...
    //终于看到创建 activity的地方了 ,见 17.2
    Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
        //进入Activity onResume
        handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);
    }
}

上面可以看到performLaunchActivity 创建了 Activity 之后,直接进入了 Activity的 onResume

那么 Activity.onCreate 一定在performLaunchActivity 中。

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ... ...

		//使用 classloader 创建一个新的 Activity ,
		/***
		public Activity newActivity(ClassLoader cl, String className,
            Intent intent)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        return (Activity)cl.loadClass(className).newInstance();
		**/
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }
     
       try {
			//获取之前创建的context  
			/**
			  创建Application
              LoadedApk.makeApplication() -> mInstrumentation.newApplication() 
			  
           static public Application newApplication(Class<?> clazz, Context context)
            throws InstantiationException, IllegalAccessException, 
            ClassNotFoundException {
				//把ContextImpl 和Application 进行绑定 
				Application app = (Application)clazz.newInstance();
				app.attach(context);
				return app;
			}			  
			**/
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);               
            if (activity != null) {
                //创建Activity 的Context
                Context appContext = createBaseContextForActivity(r, activity);  
                CharSequence title =r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);	
				//调用 activity 的 attach 方法	
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor);
                ... ...
				//调用Activity onCreate 方法  ,到此Activity 的启动最终完成了 ...真累呀....
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                ... ...
        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            ...
        }

        return activity;

}

上面可以看到 Activity 终于创建完成了,并且调用了Activity 的 onCreate 方法

其中在调用 onCreate之前还调用了 activity.attach 方法,实现 Activity 与 Context 、Window 进行绑定。

final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
        //把Context 和 Activity 进行绑定
        attachBaseContext(context);
         
        //创建window
        mWindow = new PhoneWindow(this);

        ... 
        //window 和 WindowManagerService 关联...,这样实现window 和Activity 的绑定
        mWindow.setWindowManager(
                (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                mToken, mComponent.flattenToString(),
                (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);


}

以上,Activity 的创建全部完成了。

可以看到,Acticty 的创建是 Luancher 进程和 AMS 进程多次交互的结果 。

源码

参考链接:

https://blog.csdn.net/qian520ao/article/details/78156214?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase

https://blog.csdn.net/singwhatiwanna/article/details/18154335

猜你喜欢

转载自blog.csdn.net/qq_28835333/article/details/108999792