1. 程式人生 > 其它 >Android開發涉及到的AMS類和ActivityThread類原始碼解讀

Android開發涉及到的AMS類和ActivityThread類原始碼解讀

Android開發系統啟動流程涉及到的AMS類和ActivityThread類

ZygoteInit
	- public static void main(String argv[]) {}
	- forkSystemServer()	//fork系統程序
	- mMethod.invoke(null, new Object[] { mArgs });//反射呼叫系統程序的那個ActivityThread類systemMain方法
public static ActivityThread systemMain() {	//系統的
	ActivityThread thread = new ActivityThread();
	thread.attach(true, 0);
	return thread;
}

//如果不是系統的ActivityThread,還是呼叫Looper.loop();進入死迴圈,也就是為什麼我們app不會退出的原因
ActivityThread extends ClientTransactionHandler
public static void main(String[] args) { //普通
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);	
	Looper.loop();
}

//將mAppThread傳遞給AMS系統程序
ActivityThread.attach(boolean system, long startSeq)//systemMain方法的對應為true
	- mgr.attachApplication(mAppThread, startSeq);
//首先搞清楚,是一部Android裝置系統只有一個AMS程序,並不是每個應用有一個AMS程序
//一個app應用都有一個主程序ActivityThread例項,AMS通過ProcessList mProcessList持有每個應用的程序記錄ProcessRecord
//ProcessRecord進而持有ApplicationThread代理,ApplicationThread通過H:Handler與ActivityThread通訊


//從main程序切換到AMS程序
ActivityManager.getService() 
//從AMS程序切換到main程序,通過ApplicationThread,在通過H:Handler與ActivityThread通訊
IApplicationThread mAppThread	


//App啟動後反射呼叫ActivityThread的main方法入口,然後呼叫attach方法,將IApplicationThread傳遞給AMS
//ActivityThread類的ApplicationThread幹嘛的知道了吧?就是IApplicationThread的代理類,用於和其他程序比如AMS通訊的
//1.ActivityThread
private void attach(boolean system, long startSeq) {
  	final IActivityManager mgr = ActivityManager.getService();
	mgr.attachApplication(mAppThread, startSeq);
}
//2.ActivityManagerService() 
final ActivityThread mSystemThread;	//系統程序,和AMS同一個程序的ActivityThread
final ProcessList mProcessList;	//其他程序的程序列表,管理每個程序
private boolean attachApplicationLocked(IApplicationThread thread){
    ProcessRecord app;
    generateApplicationProvidersLocked()//通過PMS獲取xml註冊的ContentProvider元件
    thread.bindApplication(processName, appInfo, providerList,...)//將providerList傳遞給主程序
    app.makeActive(thread, mProcessStats);	//持有thread:ApplicationThread
    mProcessList.updateLruProcessLocked(app, false, null);	//更新程序LRU列表
}


//每個應用的Application建立的時機:
//啟動Activity的引數ActivityClientRecord r持有packageInfo:LoadedApk持有Application mApplication
//makeApplication方法判斷有Application物件直接返回,沒有就建立一個
//ActivityThread
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    Application app = r.packageInfo.makeApplication(false, mInstrumentation);
}
Context的實現類是ContextImpl