一 app运行入口(ActivityThread)
了解过app的启动流程的之后,我们都知道app的主线程(UI线程)其实是在创建app进程的时候随之创建的,在这个线程里,有一个Handle,就是ActivityThread(注意它的名字看起来像是线程,但是根据它的继承结构来看,它其实是一个handle),负责app和Ams的通信;当我们打开一个应用的时候,就会从ActivityThread的main()方法里进入,接下来我们来看看ActivityThread的**main()**方法。
public static void main(String[] args) {
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
Looper.loop();
}
main()方法不是很长,我省略了一些无关紧要的判断,留下了关键的代码,从上面我们也能看出来ActivityThread其实就是一个handle(具体handle原理就不多说了),接着我们重点来看一下**attach()**方法 在这讲attach()方法之前,我们来普及一下三个关键的变量
public final class ActivityThread extends ClientTransactionHandler {
final H mH = new H(); 1
final ApplicationThread mAppThread = new ApplicationThread(); 2
Instrumentation mInstrumentation; 3
}
- ActivityThread 一个继承handler的一个内部类,用来接收AMS通过AppliactionThread调用ActivityThread的内部方法,来实现app的运行控制(比如Activity的生命周期方法的调用等)
- AMS和ActivityThread沟通的桥梁,ActivityThread获取AMS的代理类,然后将ApplicationThread的引用传递进代理类的相对应的方法里,这样AMS就拥有了ApplicationThread的引用,可以调用ActivityThread里的方法
- 这个其实是一个统一管理生命周期方法的类,也就是说ActivityThread不会直接调用某一个Activity的生命周期方法,而是通过这个类的引用去调用
Ok,我们回到main()方法里调用的attach()这个方法里来
ActivityThread.java —> main() -----> attach()
private void attach(boolean system, long startSeq)
{
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
attach() --> AMS.attachApplication()
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq){
ProcessRecord app;
thread.bindApplication(processName, appInfo, providers,
app.instr.mClass,
profilerInfo, app.instr.mArguments,
app.instr.mWatcher,
app.instr.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);
}
AMS.attachApplicationLocked 里调用 ActivityThread.ApplicationThread.bindApplication()
public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial, boolean autofillCompatibilityEnabled) {
AppBindData data = new AppBindData();
data.processName = processName;
data.appInfo = appInfo;
data.providers = providers;
data.instrumentationName = instrumentationName;
data.instrumentationArgs = instrumentationArgs;
data.instrumentationWatcher = instrumentationWatcher;
data.instrumentationUiAutomationConnection = instrumentationUiConnection;
data.debugMode = debugMode;
data.enableBinderTracking = enableBinderTracking;
data.trackAllocation = trackAllocation;
data.restrictedBackupMode = isRestrictedBackupMode;
data.persistent = persistent;
data.config = config;
data.compatInfo = compatInfo;
data.initProfilerInfo = profilerInfo;
data.buildSerial = buildSerial;
data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;
sendMessage(H.BIND_APPLICATION, data);
}
我们直接来看handleMesage()这个方法
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
}
ActivityThread.handleBindApplication()
private void handleBindApplication(AppBindData data) {
final ClassLoader cl = instrContext.getClassLoader();
mInstrumentation = (Instrumentation)cl.loadClass(data.instrumentationName.getClassName()).newInstance();
Application app;
app = data.info.makeApplication(data.restrictedBackupMode, null){
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
}
instrumentation.callApplicationOnCreate(app){
public void callApplicationOnCreate(Application app) {
app.onCreate();
}
};
}
创建完Application之后,我们接下来肯定是要创建Activity了,很显然,也是跟创建Application有点不一样,Application的创建我们需要从Ams里获取到Application的信息,进而通过反射创建实例,接着传入instrumentation执行它的生命周期方法,而Activity则是通过事务来创建;我们回到Ams的attachApplicationLocked ()方法中去,在创建了Application之后,还有创建Activity的逻辑 AMS.attachApplicationLocked ()
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq){
ProcessRecord app;
thread.bindApplication(processName, appInfo, providers,
app.instr.mClass,
profilerInfo, app.instr.mArguments,
app.instr.mWatcher,
app.instr.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
}
ActivityStackSupervisor .attachApplicationLocked(app).
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
final String processName = app.processName;
boolean didSomething = false;
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getChildAt(stackNdx);
if (!isFocusedStack(stack)) {
continue;
}
stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
final ActivityRecord top = stack.topRunningActivityLocked();
final int size = mTmpActivityList.size();
for (int i = 0; i < size; i++) {
final ActivityRecord activity = mTmpActivityList.get(i);
if (activity.app == null && app.uid == activity.info.applicationInfo.uid
&& processName.equals(activity.processName)) {
try {
if (realStartActivityLocked(activity, app,
top == activity , true )) {
didSomething = true;
}
}
}
ActivityStackSupervisor .realStartActivityLocked()
final boolean realStartActivityLocked (ActivityRecord r,
ProcessRecord app,boolean andResume, boolean checkConfig)
throws RemoteException {
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent), arg[]);
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
AMS.getLifecycleManager() --> ClientLifecycleManager.scheduleTransaction()
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
transaction.recycle();
}
}
ClientTransaction .schedule() **
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
Ok,我们从AMS里回到ActivityThread里来 ActivityThread.ApplicationThread.scheduleTransaction()
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
ActivityThread.scheduleTransaction()
public abstract class ClientTransactionHandler
{
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
}
ActivityThread.mH.handleMessage()
mH {
handleMessage() {
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem()) {
transaction.recycle();
}
}
}
TransactionExecutor.execute()
public class TransactionExecutor {
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
log("End resolving transaction");
}
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i)
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
}
}
}
}
LaunchActivityItem .execute()
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client);
client.handleLaunchActivity(r, pendingActions, null );
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
ActivityThead.handleLaunchActivity()
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
final Activity a = performLaunchActivity(r, customIntent);
}
ActivityThead.performLaunchActivity()
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
appContext.setOuterContext(activity);
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, window, r.configCallback);
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
}
这里最终把activity实例传入到mInstrumentation里去,里面会调用activity的onCreate()方法,此时activity就已经创建成功了。接下来看一下流程图加深一下印象
|