SystemServer.java
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
創建SystemServer對象運行run()方法,點入run() 方法
//啓動服務的關鍵代碼
Start services.
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
進入startBootstrapServices() 可以看到啓動ActivityManagerService的代碼
//mActivityManagerService 通過反射啓動AMS 服務
// Activity manager runs the show.
traceBeginAndSlog("StartActivityManager");
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
traceEnd();
SystemServiceManager 啓動服務的代碼,可以看到到就是就是通過Class.forName()
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
Slog.i(TAG, "Starting " + className);
throw new RuntimeException("Failed to create service " + className
+ ": service class not found, usually indicates that the caller should "
+ "have called PackageManager.hasSystemFeature() to check whether the "
+ "feature is available on this device before trying to start the "
+ "services that implement it", ex);
}
return startService(serviceClass);
}
AMS 通過靜態內部類啓動
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
super(context);
//創建AMS實例
mService = new ActivityManagerService(context);
}
@Override
public void onStart() {
//啓動AMS 服務對象
mService.start();
}
public ActivityManagerService getService() {
//獲取實例對象
return mService;
}
}
我們的AMS已經啓動了,接着我們點擊桌面上的圖標以後就要啓動我們的app了。
先上一張時序圖
用戶在Launcher程序裏點擊應用圖標時,會通知ActivityManagerService啓動應用的主Activity,ActivityManagerService發現這個應用還未啓動,則會通知Zygote進程孵化出應用進程,然後在這個新孵化的應用進程裏執行ActivityThread的main方法。
讓我們先來看看ActivityThread 這個線程幹了什麼
public static void main(String[] args) {
····
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
···
Looper.loop();
···
}
… 未完待續