1、无论是要隐式启动还是显示启动最后调用到的都是startActivityForResult(),最后调用AMS的startActivity()
2、PMS检测要启动的Activity是否存在
3、到AMS会创建ActivityRecord用于管理AMS中的Activity。这个功能由ActivityStackSupervisor负责。
4、获取启动模式使用ActivityStack存储
5、ActivityStack的管理也是基于栈的、将启动的ActivityStack放到栈顶
6、执行上一个Activity的pause()方法
7、检测要启动Activity的进程是否存在
if (next.app != null && next.app.thread != null) {
...
} else {
...
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
next.app是ProcessRecord 应用进程启动后会通知AMS更新这个值
next.app.thread 是ApplicationThread用于跟引用进程通信的,应用进程启动后会通知AMS这个值
Process.start() 使用socket通讯zygote()进程去fork()一个新的进程用于启动Activity
8、进程启动后会调用到ActivityThread的main方法
public static void main(String[] args) {
...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
...
Looper.loop();
...
}
启动主线程
创建ActivityThread
执行attach方法
开启消息循环
重点关注attach方法,他会调用AMS的attachApplication方法通知AMS应用进程创建成功,然后AMS会通过ApplicationThread调用App的scheduleLaunchActivity(),到App中使用Message机制调用handleLaunchActivity()
private void handleLaunchActivity() {
// 执行启动 Activity
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
// resume activity
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
} else {
}
}
performLaunchActivity()中会执行attach方法用于创建Activity的Context,创建Window对象和设置WindowManager。
private performLaunchActivity() {
// 创建 context
···
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
// 构建 Activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
···
}
然后,然后调用onCreate,onStart,
final void handleResumeActivity() {
r = performResumeActivity();
if(r != null) {
final Activity a = r.activity;
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
// window
wm.addView(decor, l);
}
}
}
}
}
handleResume会真正的让View显示处理
handleResumeActivity方法内完成了如下工作:
回调Activity的onResume方法
调用WindowManager的addView方法,将前面在attach方法内创建出来的window对象添加到WindowManager当中。
参照
https://www.jianshu.com/p/2bed70245c76
https://juejin.im/entry/58f5b68e61ff4b005807ab47
https://juejin.im/entry/5abdcdea51882555784e114d
https://blog.csdn.net/TellH/article/details/57418651
https://zhuanlan.zhihu.com/p/67451239
https://alleniverson.gitbooks.io/android/chapter3/1.%20Activity/1.%20Activity%E5%90%AF%E5%8A%A8%E8%BF%87%E7%A8%8B.html
http://gityuan.com/2016/03/12/start-activity/
http://crazysunj.com/2017/07/16/%E5%9B%BE%E8%A7%A3Activity%E5%90%AF%E5%8A%A8%E6%B5%81%E7%A8%8B%EF%BC%8C%E8%BF%9B%E9%98%B6%E9%AB%98%E7%BA%A7/