美文网首页
App启动流程大致梳理

App启动流程大致梳理

作者: 瑜小贤 | 来源:发表于2019-12-02 16:54 被阅读0次

Java程序入口是 main方法,Android程序有没有main方法呢?
有的,Android的main方法在ActivityThread类中。
注:ActivityThread继承自ClientTransactionHandler,从这个父类中的abstract方法(handleResumeActivity,handlePauseActivity等)可以看出,其中有很多管理activity生命周期的方法。

在ActivityThread类底部,就能看到public static void main(String[] args) 方法了
在这个方法中首先做了初始化,然后我们依次来捋一捋步骤

ActivityThread类
public static void main(String[] args) {
  ...
  Environment.initForCurrentUser(); //初始化环境
  ...
  ActivityThread thread = new ActivityThread(); //初始化ActivityThread
  thread.attach(false, startSeq); //关键代码
  ...
}

/*
* ActivityThread类中的attach方法
*/
private void attach(boolean system, long startSeq) {
//关键代码
//获得ActivityManagerService
  final IActivityManager mgr = ActivityManager.getService(); 
  try {
      mgr.attachApplication(mAppThread, startSeq); //关键代码
  } catch (RemoteException ex) {
      throw ex.rethrowFromSystemServer();
  }
}

...

ActivityManagerService类
/*
* ActivityManagerService类中的attachApplication方法
*/
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid(); //获取进程id
        final int callingUid = Binder.getCallingUid(); //获取uid
        final long origId = Binder.clearCallingIdentity(); 
        attachApplicationLocked(thread, callingPid, callingUid, startSeq); //关键代码
        Binder.restoreCallingIdentity(origId);
    }
}


private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
...
if (app.isolatedEntryPoint != null) {
                // This is an isolated process which should just call an entry point instead of
                // being bound to an application.
                thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
            } else if (instr2 != null) {
                //关键代码,thread是作为参数传入的ActivityManagerService
                thread.bindApplication(processName, appInfo, providers,
                        instr2.mClass,
                        profilerInfo, instr2.mArguments,
                        instr2.mWatcher,
                        instr2.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.isPersistent(),
                        new Configuration(app.getWindowProcessController().getConfiguration()),
                        app.compat, getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, autofillOptions, contentCaptureOptions);
            } else {
                thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                        null, null, null, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.isPersistent(),
                        new Configuration(app.getWindowProcessController().getConfiguration()),
                        app.compat, getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, autofillOptions, contentCaptureOptions);
            }
...
}

...

回到ActivityThread类
/*
* ActivityThread类中的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, AutofillOptions autofillOptions,
                ContentCaptureOptions contentCaptureOptions) {
...
    //关键代码
    sendMessage(H.BIND_APPLICATION, data);
}

//内部类
class H extends Handler {
    public void handleMessage(Message msg) {
            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;
            }
    }
}



private void handleBindApplication(AppBindData data) {
...
try {
        mInstrumentation.onCreate(data.instrumentationArgs); 
} 
catch (Exception e) {
        throw new RuntimeException(
                "Exception thrown in onCreate() of "
                + data.instrumentationName + ": " + e.toString(), e);
}
try {
        //关键代码,这里就会调用Application的onCreate
        mInstrumentation.callApplicationOnCreate(app); 
} catch (Exception e) {
        if (!mInstrumentation.onException(app, e)) {
                throw new RuntimeException(
                "Unable to create application " + app.getClass().getName()
                + ": " + e.toString(), e);
        }
}
...
}

...

另一条线

ActivityManagerService类
private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
...
        // See if the top visible activity is waiting to run in this process...
        if (normalMode) {
            try {
                //mAtmInternal是向LocalService中添加的ActivityTaskManagerService类的实例
                didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
            } catch (Exception e) {
                badApp = true;
            }
        }
...
}

...

ActivityTaskManagerService类
//内部类
final class LocalService extends ActivityTaskManagerInternal {
        @HotPath(caller = HotPath.PROCESS_CHANGE)
        @Override
        public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
            synchronized (mGlobalLockWithoutBoost) {
                return mRootActivityContainer.attachApplication(wpc);
            }
        }
}

...

RootActivityContainer类
boolean attachApplication(WindowProcessController app) throws RemoteException {
        try {
            //关键代码
            if (mStackSupervisor.realStartActivityLocked(activity, app, 
                    top == activity /* andResume */, true /* checkConfig */)) {
                didSomething = true;
            }
        } catch (RemoteException e) {
            throw e;
        }
}

...

ActivityStackSupervisor类
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
...
        // Create activity launch transaction.
        final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.appToken);

        final DisplayContent dc = r.getDisplay().mDisplayContent;
        clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                System.identityHashCode(r), r.info,
                mergedConfiguration.getGlobalConfiguration(),
                mergedConfiguration.getOverrideConfiguration(), r.compat,
                r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                r.icicle, r.persistentState, results, newIntents,
                dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                r.assistToken));

        // Set desired final state.
        final ActivityLifecycleItem lifecycleItem;
        if (andResume) {
              lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
        } else {
            lifecycleItem = PauseActivityItem.obtain();
        }
        clientTransaction.setLifecycleStateRequest(lifecycleItem);
        // 关键代码
        mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
}

...

ClientLifecycleManager类
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
....
        final IApplicationThread client = transaction.getClient();
        transaction.schedule(); //关键代码
 ...
}

...

ClientTransaction类
private IApplicationThread mClient;
public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this); //关键代码
}

...

回到ActivityThread类(IApplicationThread的实现类)
void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

//内部类
class H extends Handler {
...
public void handleMessage(Message msg) {
        switch (msg.what) {
            case EXECUTE_TRANSACTION:
                final ClientTransaction transaction = (ClientTransaction) msg.obj;
                mTransactionExecutor.execute(transaction); //关键代码
                if (isSystem()) {
                    transaction.recycle();
                }
                break;
        }
...
}

...

TransactionExecutor类
public void execute(ClientTransaction transaction) {
        final IBinder token = transaction.getActivityToken();
        if (token != null) {
            final Map<IBinder, ClientTransactionItem> activitiesToBeDestroyed =
                    mTransactionHandler.getActivitiesToBeDestroyed();
            final ClientTransactionItem destroyItem = activitiesToBeDestroyed.get(token);
            if (destroyItem != null) {
                if (transaction.getLifecycleStateRequest() == destroyItem) {
                    activitiesToBeDestroyed.remove(token);
                }
                if (mTransactionHandler.getActivityClient(token) == null) {
                    return;
                }
            }
        }
        executeCallbacks(transaction); //关键代码
        executeLifecycleState(transaction); 
        mPendingActions.clear();
    }

public void executeCallbacks(ClientTransaction transaction) {
    //此callbacks是ActivityStackSupervisor的realStartActivityLocked方法中
    //通过clientTransaction.addCallback方法添加进的LaunchActivityItem(ClientTransactionItem的实现类)
    final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    ...
    for (int i = 0; i < size; ++i) {
        ...
        item.execute(mTransactionHandler, token, mPendingActions); //关键代码
        item.postExecute(mTransactionHandler, token, mPendingActions);
        ...
    }
    ...
}

...

LaunchActivityItem类(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, mAssistToken);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */); //关键代码
    }

...

回到ActivityThread(ClientTransactionHandler的子类)
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
    ...
    final Activity a = performLaunchActivity(r, customIntent);
    ...

}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    activity.mCalled = false;
    if (r.isPersistable()) {
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); //关键代码
    } else {
        mInstrumentation.callActivityOnCreate(activity, r.state);
    }
    ...
}

...

Instrumentation类
public void callActivityOnCreate(Activity activity, Bundle icicle,
            PersistableBundle persistentState) {
        prePerformCreate(activity); 
        activity.performCreate(icicle, persistentState); //关键代码
        postPerformCreate(activity);
}
图片示意

相关文章

网友评论

      本文标题:App启动流程大致梳理

      本文链接:https://www.haomeiwen.com/subject/fcoxgctx.html