//ActivityThread.java
public static void main(String[] args) {
Environment.initForCurrentUser();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
// 调用attach
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
}
private void attach(boolean system) {
sCurrentActivityThread = this;
mSystemThread = system;
//非系统app
if (!system) {
android.ddm.DdmHandleAppName.setAppName("",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
//获取ActivityManager
final IActivityManager mgr = ActivityManager.getService();
try {
//ActivityManagerService的attachApplication()方法来实现Activity的调度工作
//之后ActivityThread的scheduleLaunchActivity()调用
//通过hander的H.LAUNCH_ACTIVITY调用handleLaunchActivity
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
// Watch for getting close to heap limit.
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
if (dalvikUsed > ((3*dalvikMax)/4)) {
if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
+ " total=" + (runtime.totalMemory()/1024)
+ " used=" + (dalvikUsed/1024));
mSomeActivitiesChanged = false;
try {
mgr.releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
});
}
}
Activity启动后依次调用了attach方法,用作初始化Window和WindowManager对象,然后就进入了Activity的生命启动周期,onCreate->onStart->onRestoreInstanceState->onResume,当Activity处于Stop状态的时候,调用onRestart->onStart->onResume
//在ActivityThread.java中有一个handleLaunchActivity函数,是创建Activity的地方
// 创建Activity的入口
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
// Initialize before creating the activity
WindowManagerGlobal.initialize();
// 返回一个Activity
Activity a = performLaunchActivity(r, customIntent);
......
// handleResumeActivity?跟Activity的onResume方法有何关系?
handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed);
......
// 看这个函数的名字,调用Activity的onPause方法
mInstrumentation.callActivityOnPause(r.activity);
......
}
//WindowManagerGlobal::initialize()目的是获取WindowManagerService,代码会走到
//WindowManagerGlobal的函数IWindowManager getWindowManagerService()
public static IWindowManager getWindowManagerService() {
synchronized (WindowManagerGlobal.class) {
if (sWindowManagerService == null) {
//此处获取WindowManagerService
sWindowManagerService = IWindowManager.Stub.asInterface(
ServiceManager.getService("window"));
try {
if (sWindowManagerService != null) {
ValueAnimator.setDurationScale(
sWindowManagerService.getCurrentAnimatorScale());
}
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
return sWindowManagerService;
}
}
//ActivityThread::performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
// 调用Instrumentation.java文件的newActivity方法
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
......
// 调用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);
......
// 调用Instrumentation的callActivityOnCreate方法,从名字上看,是调用了Activity的onCreate方法?
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
......
// 调用Activity的performStart方法
activity.performStart();
r.stopped = false;
......
// 调用Instrumentation的callActivityOnRestoreInstanceState方法
if (r.isPersistable()) {
if (r.state != null || r.persistentState != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state, r.persistentState);
}
} else if (r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
......
// 调用Instrumentation的callActivityOnPostCreate方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnPostCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnPostCreate(activity, r.state);
}
......
}
//Instrumentation::newActivity
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
return (Activity)cl.loadClass(className).newInstance();
}
//Activity::attach
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,
Window window, ActivityConfigCallback activityConfigCallback) {
........
//// 初始化PhoneWindow对象
mWindow = new PhoneWindow(this, window, activityConfigCallback);
mWindow.setWindowControllerCallback(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);
.........
mUiThread = Thread.currentThread();
mMainThread = aThread;
mInstrumentation = instr;
mToken = token;
mIdent = ident;
mApplication = application;
.......
//设置并获取WindowManager
mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
if (mParent != null) {
mWindow.setContainer(mParent.getWindow());
}
mWindowManager = mWindow.getWindowManager();
mWindow.setColorMode(info.colorMode);
}
//Activity中的mWindow为PhoneWindow对象,而mWindowManager为WindowManagerIpml对象
/**
* Set the window manager for use by this Window to, for example,
* display panels. This is not used for displaying the
* Window itself -- that must be done by the client.
*
* @param wm The window manager for adding new windows.
*/
public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
boolean hardwareAccelerated) {
mAppToken = appToken;
mAppName = appName;
mHardwareAccelerated = hardwareAccelerated
|| SystemProperties.getBoolean(PROPERTY_HARDWARE_UI, false);
if (wm == null) {
wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
}
mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
}
//Instrumentation::callActivityOnCreate
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
//Activity::performCreate
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
......
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
......
}
//ActivityThread::handleLaunchActivity
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume) {
......
// TODO Push resumeArgs into the activity for consideration
ActivityClientRecord r = performResumeActivity(token, clearHide);
......
}
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide) {
......
r.activity.performResume();
......
}
//Activity.java
final void performResume() {
// 调用performRestart方法
performRestart();
......
// mResumed is set by the instrumentation
// 调用Instrumentation的callActivityOnResume方法,即调用Activity的onResume方法
mInstrumentation.callActivityOnResume(this);
......
}
final void performRestart() {
......
// 调用Instrumentation的callActivityOnRestart方法,主要是调用Activity的onRestart方法
mInstrumentation.callActivityOnRestart(this);
......
performStart();
}
final void performRestart() {
......
// 调用Instrumentation的callActivityOnRestart方法,主要是调用Activity的onRestart方法
mInstrumentation.callActivityOnRestart(this);
......
performStart();
}
public void callActivityOnRestart(Activity activity) {
// 调用Activity的onRestart方法
activity.onRestart();
}
final void performStart() {
......
// 调用Insttumentation的callActivityOnstart方法,之后调用Activity的onStart方法
mInstrumentation.callActivityOnStart(this);
......
}
//Instrumentation.java
public void callActivityOnStart(Activity activity) {
activity.onStart();
}
//Activity.java
final void performResume() {
// 调用performRestart方法
performRestart();
......
// mResumed is set by the instrumentation
// 调用Instrumentation的callActivityOnResume方法,即调用Activity的onResume方法
mInstrumentation.callActivityOnResume(this);
......
}
下图来自 https://www.jianshu.com/p/d4cc363813a7