Android上一个应用的入口,应该是ActivityThread,它和普通的java类一样,入口是一个main方法。
public static void main(String[] args) {
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
Security.addProvider(new AndroidKeyStoreProvider());
// 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();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
更进一步而言,其实是Launcher类来解析Activity的信息和调用onCreate方法。
要想弄清楚android应用程序的入口,可以从堆栈入手:
NaiveStart.main()
ZygoteInit.main
ZygoteInit$MethodAndArgsCall.run
Method.Invoke method.invokeNative
ActivityThread.main()
Looper.loop()
ActivityThread$H(Handler).dispathMessage(Message)
ActivityThread$H.handleMessage(Message)
ActivityThread.performLaunchActivity
Instrumentation.callActivityOnCreate(Activity,Bundle)
MainActivity(Activity).performCreate(Bundle)
MainActivity.onCreate(Bundle)
App按钮控件中设置异常的堆栈:
not provide monitor information>
MainActivity$1.onClick(View) line: 26
Button(View).performClick() line: 4470
View$PerformClick.run() line: 18599
Handler.handleCallback(Message) line: 733
ViewRootImpl$ViewRootHandler(Handler).dispatchMessage(Message) line: 95
Looper.loop() line: 157
ActivityThread.main(String[]) line: 5633
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 515
ZygoteInit$MethodAndArgsCaller.run() line: 896
ZygoteInit.main(String[]) line: 712
NativeStart.main(String[]) line: not available [native method]
从上述堆栈可知所有应用程序的入口都是ActivityThread.main中的looper.loop()开始的。
现在就有个问题,ActivityThread是如何建立的呢?
1. AcitivityManager产生新进程,新进程从android.app.ActivityThread.main开始运行。这里就是一般意义上的程序入口点,类似于C的main函数。
ActivityManagerService.java
private final void startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr) {
// Process里面通知Zygote服务,Zygote真正产生新的进程(准确说是复制一个)
int pid = Process.start("android.app.ActivityThread",
mSimpleProcessManagement ? app.processName : null, uid, uid,
}
2.ActivityThread的main函数中将Looper准备起来,prepareMainLooper标志着这是应用程序主线程的Looper对象。
ActivityThread.java
public static final void main(String[] args) {
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
// 这里闭合消息循环
Looper.loop();
}
3.接下来调用attach,参数为false,表明这不是系统进程,是给普通应用程序用使用的进程。
ActivityThread.java
private final void attach(boolean system) {
ViewRoot.addFirstDrawHandler(new Runnable() {
public void run() {
ensureJitEnabled();
}
});
RuntimeInit.setApplicationObject(mAppThread.asBinder());
IActivityManager mgr = ActivityManagerNative.getDefault();
mgr.attachApplication(mAppThread);
}
4.mAppThread是ApplicationThread对象,是提供给ActivityManagerService控制ActivityThread的回调接口.
private final class ApplicationThread extends ApplicationThreadNative {
public final void schedulePauseActivity(IBinder token, boolean finished,boolean userLeaving, int configChanges){
queueOrSendMessage(finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token, (userLeaving ? 1 : 0), configChanges);
}
public final void scheduleStopActivity(IBinder token, boolean showWindow, int configChanges) {
queueOrSendMessage(showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
token, 0, configChanges);
}
.........
}
ActivityManagerService要Pause当前Activity,就会调用schedulePauseActivity想本地的消息循环中加入一个H.PAUSE_ACTIVITY的消息,然后立即返回以避免ActivityManagerService的阻塞。
5.现在又回到了ActivityManagerService中
ActivityManagerService.java
// ActivityManagerService中XXXLocked函数才是真正干活的地方,XXX只是个套
public final void attachApplication(IApplicationThread thread) {
int callingPid = Binder.getCallingPid();
attachApplicationLocked(thread, callingPid);
}
private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {
// 这里取出对应该Pid的ProcessRecord对象,如果取不出来,你就等着out吧
app = mPidsSelfLocked.get(pid)
// 为ProcessRecord对象补充信息
app.thread = thread;
app.curAdj = app.setAdj = -100;
app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
app.forcingToForeground = null;
app.foregroundServices = false;
app.debugging = false;
// 清除timeout监测
mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
// 回调之前的ActivityThread,让它记住自己在ActivityManagerService中的相关信息,传这么大坨东西,真给力
thread.bindApplication(processName, app.instrumentationInfo != null
app.instrumentationInfo : app.info, providers,
app.instrumentationClass, app.instrumentationProfileFile,
app.instrumentationArguments, app.instrumentationWatcher, testMode,
isRestrictedBackupMode || !normalMode,
mConfiguration, getCommonServicesLocked());
// topRunningActivityLocked的意思没看太明白
HistoryRecord hr = topRunningActivityLocked(null);
// 启动Activity
realStartActivityLocked(hr, app, true, true);
}
private final boolean realStartActivityLocked(HistoryRecord r,
ProcessRecord app, boolean andResume, boolean checkConfig){
// 这里又跑到ActivityThread中去了
app.thread.scheduleLaunchActivity(new Intent(r.intent), r, System.identityHashCode(r),
r.info, r.icicle, results, newIntents, !andResume, isNextTransitionForward());
}
6.ActivityThread开始调度用户的Activity启动了
ActivityThread.java
private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
Activity a = performLaunchActivity(r, customIntent);
......
}
private final void performLaunchActivity(ActivityRecord r, Intent customIntent) {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
// 产生Activity
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
// 将新生的Activity与当前应用关联
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstance,
r.lastNonConfigurationChildInstances, config);
.....
}
7.Acivity与当前App关联,直到这里,平时应用所见的Activity才真正被构建
Actiivty.java
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,
Object lastNonConfigurationInstance, HashMap lastNonConfigurationChildInstances,
Configuration config) {
// 记录传入ContexImpl实例,这就是平时所见的Activity Context
attachBaseContext(context);
// 创建与Activity关联的Window,可以简单理解为显示窗口
mWindow = PolicyManager.makeNewWindow(this);
mUiThread = Thread.currentThread();
mMainThread = aThread;
mInstrumentation = instr;
mToken = token;
mIdent = ident;
mApplication = application;
mIntent = intent;
mComponent = intent.getComponent();
mActivityInfo = info;
mTitle = title;
mParent = parent;
mEmbeddedID = id;
// 构建WindowManager的代理LocalWindowManager
mWindow.setWindowManager(null, mToken, mComponent.flattenToString());
if (mParent != null) {
// 难道说整个Activity栈中的Activity都有同一个Container
mWindow.setContainer(mParent.getWindow());
}
mWindowManager = mWindow.getWindowManager();
}
8.ActivityThread
ActivityThread.java
private final void performLaunchActivity(ActivityRecord r, Intent customIntent) {
......
// 回调Activity::onCreate
mInstrumentation.callActivityOnCreate(activity, r.state);
// 记录新产生的Activity
mActivities.put(r.token, r);
}
private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
......
handleResumeActivity(r.token, false, r.isForward);
}
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
ActivityRecord r = performResumeActivity(token, clearHide);
}
public final ActivityRecord performResumeActivity(IBinder token, boolean clearHide) {
if (r.pendingIntents != null) {
deliverNewIntents(r, r.pendingIntents);
r.pendingIntents = null;
}
if (r.pendingResults != null) {
deliverResults(r, r.pendingResults);
r.pendingResults = null;
}
//回调Activity::onResume
r.activity.performResume();
}
到这里,Activity从产生到初始化的过程就全部结束了。之后就是等待用户界面的消息,根据消息进行相应的处理。整个过程中,在ActivityManagerServer、ActivityThread的互相协作下构建出Activity,并在相应的时机回调Activity的相应接口,完成Activity的初始化