Launcher的Activity.onCreate

进入 ActivityThread.main,最终完成 Launcher.onCreate 操作
Zygote fork 出了 Launcher 进程,并把接下来的 Launcher 启动任务交给了 ActivityThread 来进行,接下来就从 ActivityThread.main 方法来分析 Launcher 的创建过程。 以下是 ActivityThread 启动 Activity 的时序图:


ActivityThread.main 方法是程序入口,以下是相关代码:

// /frameworks/base/core/java/android/app/ActivityThread.java
public static void main(String[] args) {
    ...
    Looper.prepareMainLooper();
    ...
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq); // 1

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    ...  
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

在注释 1 处调用 ActivityThread.attach 方法,以下是相关源码:

```java
// /frameworks/base/core/java/android/app/ActivityThread.java
@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        ...
        final IActivityManager mgr = ActivityManager.getService(); // 1
        try {
            mgr.attachApplication(mAppThread, startSeq); // 2
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        ...
    } else {
        ...
    }
    ...
}

在注释 1 处获取 ActivityManagerService 的实例,在注释 2 处调用 ActivityManagerService.attachApplication 方法:

// /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
    if (thread == null) {
        throw new SecurityException("Invalid application interface");
    }
    synchronized (this) {
        // 通过 Binder 获取传入的 pid 信息
        int callingPid = Binder.getCallingPid(); 
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid, callingUid, startSeq); // 1
        Binder.restoreCallingIdentity(origId);
    }
}

public ActivityTaskManagerInternal mAtmInternal;
@GuardedBy("this")
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
                                        int pid, int callingUid, long startSeq) {
    ...
    didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); // 2
    ...
}

在注释 1 处调用了 ActivityManagerService.attachApplicationLocked 方法。注释 2 处的 mAtmInternal 是 ActivityTaskManagerInternal 类型的变量, ActivityTaskManagerService 中的内部类 LocalService 继承自 ActivityTaskManagerInternal,以下是相关源码:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
final class LocalService extends ActivityTaskManagerInternal {
    @HotPath(caller = HotPath.PROCESS_CHANGE)
    @Override
    public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
        synchronized (mGlobalLockWithoutBoost) {
            return mRootActivityContainer.attachApplication(wpc); // 1
        }
    }
}

在注释 1 处调用了RootActivityContainer.attachApplication 方法:

// frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
boolean attachApplication(WindowProcessController app) throws RemoteException {
    final String processName = app.mName;
    boolean didSomething = false;
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.get(displayNdx);
        final ActivityStack stack = display.getFocusedStack();
        if (stack != null) {
            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.mUid == activity.info.applicationInfo.uid
                    && processName.equals(activity.processName)) {
                    try {
                        // 1
                        if (mStackSupervisor.realStartActivityLocked(activity, app,
                                                            top == activity /* andResume */, 
                                                                     true /* checkConfig */)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                        Slog.w(TAG, "Exception in new application when starting activity "
                               + top.intent.getComponent().flattenToShortString(), e);
                        throw e;
                    }
                }
            }
        }
    }
    if (!didSomething) {
        ensureActivitiesVisible(null, 0, false /* preserve_windows */);
   }
    return didSomething;
}

在注释 1 处调用 ActivityStackSupervisor.realStartActivityLocked 方法:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
                                boolean andResume, boolean checkConfig) throws RemoteException {
    ...
    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)); // 1

    ...
    // Schedule transaction.
    mService.getLifecycleManager().scheduleTransaction(clientTransaction); // 2 
    ...
}

注释 2 处 ActivityTaskManagerService.getLifecycleManager 方法返回 ClientLifecycleManager 实例。以下是 ClientLifecycleManager.scheduleTransaction 的相关源码:

// /frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    transaction.schedule(); // 1
    if (!(client instanceof Binder)) {
        // If client is not an instance of Binder - it's a remote call and at this point it is
        // safe to recycle the object. All objects used for local calls will be recycled after
        // the transaction is executed on client in ActivityThread.
        transaction.recycle(); 
    }
}

在注释 1 处调用了 ClientTransaction.schedule 方法:

// /frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
private IApplicationThread mClient; 
public void schedule() throws RemoteException {
    mClient.scheduleTransaction(this); // 1
}

注释 1 处的 mClient 是 IApplicationThread 实例,在这里是 ApplicationThread,ApplicationThread 是 ActivityThread 的内部类,以下是相关源码:

// /frameworks/base/core/java/android/app/ClientTransactionHandler.java
void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); // 1


注释 1 处的 ActivityThread.H 是 Handler 的子类,以下是 ActivityThread.sendMessage 方法的源码和关于 ActivityThread.H.EXECUTE_TRANSACTION 的相关处理:

// /frameworks/base/core/java/android/app/ActivityThread.java
void sendMessage(int what, Object obj) {
    sendMessage(what, obj, 0, 0, false);
}

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
    if (DEBUG_MESSAGES) {
        Slog.v(TAG,
               "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
    }
    Message msg = Message.obtain();
    msg.what = what;
    msg.obj = obj;
    msg.arg1 = arg1;
    msg.arg2 = arg2;
    if (async) {
        msg.setAsynchronous(true);
    }
    mH.sendMessage(msg);
}

class H extends Handler {
    ...
    public static final int EXECUTE_TRANSACTION = 159;
    ...
    public void handleMessage(Message msg) {
        if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
        switch (msg.what) {
            ...
            case EXECUTE_TRANSACTION:
                final ClientTransaction transaction = (ClientTransaction) msg.obj;
                mTransactionExecutor.execute(transaction); // 1
                if (isSystem()) {
                    // Client transactions inside system process are recycled on the client side
                    // instead of ClientLifecycleManager to avoid being cleared before this
                    // message is handled.
                    transaction.recycle();
                }
                // TODO(lifecycler): Recycle locally scheduled transactions.
                break;
                ...
        }
    }
}

在注释 1 处调用了 TransactionExecutor.execute 方法

// /frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public void execute(ClientTransaction transaction) {
    ...
    executeCallbacks(transaction); // 1

    executeLifecycleState(transaction);
    mPendingActions.clear();
    if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
}

@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
    ...
    final int size = callbacks.size();
    for (int i = 0; i < size; ++i) {
        final ClientTransactionItem item = callbacks.get(i);
        ...
        item.execute(mTransactionHandler, token, mPendingActions); // 2
        ..    }
}

注释 2 处调用了 ClientTransactionItem.execute 方法,该方法在其子类 LaunchActivityItem 中实现,以下是 LaunchActivityItem.execute 方法:

// /frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java) 
@Override
public void execute(ClientTransactionHandler client, IBinder token,
                    PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
    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 */); // 1
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

注释 1 处的 client 是 ClientTransactionHandler 的子类 ActivityThread,查看 ActivityThread.handleLauncherActivity 的源码,主要是调用了 ActivityThread.performLaunchActivity 方法:

// /frameworks/base/core/java/android/app/ActivityThread.java
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
                                     PendingTransactionActions pendingActions, 
                                     Intent customIntent) {
    ...
    WindowManagerGlobal.initialize();

    // 1 启动 Activity
    final Activity a = performLaunchActivity(r, customIntent);

    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        if (!r.activity.mFinished && pendingActions != null) {
            pendingActions.setOldState(r.state);
            pendingActions.setRestoreInstanceState(true);
            pendingActions.setCallOnPostCreate(true);
        }
    } else {
        // If there was an error, for any reason, tell the activity manager to stop us.
        try {
            // 停止 Activity 的启动
            ActivityTaskManager.getService()
                .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

    return a;
}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ActivityInfo aInfo = r.activityInfo; // 2 获取 ActivityInfo 类
    if (r.packageInfo == null) {
        // 3 获取 APK 文件描述类 LoadApk
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                                       Context.CONTEXT_INCLUDE_CODE); 
    }

    ComponentName component = r.intent.getComponent(); // 4
    ...
    // 5 创建要启动的 Activity 的上下文环境
    ContextImpl appContext = createBaseContextForActivity(r); 
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        // 6 用类加载器创建该 Activity 的实例
        activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
        ...
    } catch (Exception e) {
        ...
    }

    try {
        // 7 创建 Application
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        ...
        if (activity != null) {
            ...
            // 8 初始化 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,
                            r.assistToken);
            ...
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); // 9
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
        }
        ...
    } catch (SuperNotCalledException e) {
        throw e;

    } catch (Exception e) {
        ....
    }
    return activity;
}

注释 1 处调用了 ActivityThread.performLaunchActivity 方法来启动 Activity。注释 2 处用来获取 ActivityInfo,用来存储代码以及 AndroidManifest 设置的 Activity 和 Receiver 节点信息,比如,Activity 的 theme 和 launchMode。在注释 3 处获取 APK 文件的描述类 LoadedApk。在注释 4 处获取要启动的 Activity 的 ComponentName 类,在 ComponentName 类中保存了该 Activity 的包名和类名。在注释 5 处用来创建要启动的 Activity 的上下文环境。在注释 6 处根据 ComponentName 中存储的 Activity 类名,用类加载器来创建该 Activity 的实例 。注释 7 处用来创建 Application,LoadedApk.makeApplication 方法内部会调用 Application.onCreate 方法。注释 8 处调用 Activity.attach 方法初始化 Activity,在 Activity.attach 方法中会创建 Window 对象(PhoneWindow)并与 Activity 自身进行关联。在注释 9 处调用 Instrumentation.callActivityOnCreate 方法来启动 Activity:

// /frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle,
                                 PersistableBundle persistentState) {
    prePerformCreate(activity);
    activity.performCreate(icicle, persistentState); // 1
    postPerformCreate(activity);
}

注释 1 处调用了 Activity.performCreate 方法,在 Activity.performCreate 方法中又调用了 Activity.onCreate 方法,到这里,根 Activity 就启动了,以下是相关源码:

// /frameworks/base/core/java/android/app/Activity.java
@UnsupportedAppUsage
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    dispatchActivityPreCreated(icicle);
    mCanEnterPictureInPicture = true;
    restoreHasCurrentPermissionRequest(icicle);
    // 1
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
    mActivityTransitionState.readState(icicle);

    mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
        com.android.internal.R.styleable.Window_windowNoDisplay, false);
    mFragments.dispatchActivityCreated();
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    dispatchActivityPostCreated(icicle);
}

@MainThread
@CallSuper
protected void onCreate(@Nullable Bundle savedInstanceState) {
    if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);

    if (mLastNonConfigurationInstances != null) {
        mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
    }
    if (mActivityInfo.parentActivityName != null) {
        if (mActionBar == null) {
            mEnableDefaultActionBarUp = true;
        } else {
            mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
        }
    }
    if (savedInstanceState != null) {
        mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
        mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
                                                    View.LAST_APP_AUTOFILL_ID);

        if (mAutoFillResetNeeded) {
            getAutofillManager().onCreate(savedInstanceState);
        }

        Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
        mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
                                   ? mLastNonConfigurationInstances.fragments : null);
    }
    mFragments.dispatchCreate();
    dispatchActivityCreated(savedInstanceState);
    if (mVoiceInteractor != null) {
        mVoiceInteractor.attachActivity(this);
    }
    mRestoredFromBundle = savedInstanceState != null;
    mCalled = true;

}

public void onCreate(@Nullable Bundle savedInstanceState,
                     @Nullable PersistableBundle persistentState) {
    onCreate(savedInstanceState);
}



本站内容来源于作者发布和网络转载,如有版权相关问题请及时与我们取得联系,我们将立即删除。

 关于作者
 热门教程
系统启动流程
1、BootRom 启动电源以及系统启动。 当电源按下时,引导芯片代码从预定义的地方(固化在ROM中)开始执行。加载引
2023-09-10
剑道仙尊
54
Android源码开始
Framework源码下载: https://android.googlesource.com/platform/fr
2023-09-10
剑道仙尊
57
Launcher的Activity.onCreate
进入 ActivityThread.main,最终完成 Launcher.onCreate 操作 Zygote for
2022-09-11
剑道仙尊
41
Launcher启动流程
Launcher介绍 系统启动的最后一步是启动一个应用程序来显示系统中已经安装的应用程序,这个应用程序就叫做 Laun
2022-09-11
剑道仙尊
43
创建Launcher进程
Zygote进程接收请求并创建 Launcher进程 想要启动一个应用程序,首先要保证这个应用程序所需要的应用程序进程
2022-09-11
剑道仙尊
46
Launcher的配置
Launcher 的配置 在 SystemServer.startOtherServices 方法中调用Activit
2022-09-11
剑道仙尊
46
PackageManagerService
PackageManagerService( PMS ) 1、PMS会把每个apk进行扫描,然后分别把每个apk里的信
2022-09-11
剑道仙尊
42
WindowManagerService
待更新。。。
2022-09-11
剑道仙尊
28
ActivityManagerService
ActivityManagerService(AMS)主要负责系统中四大组件的启动、切换、调度以及应用程序的管理和调度
2022-09-11
剑道仙尊
52
systemserver进程
system server进程是由zygote进程fork出来的,在上面的ZygoteInit.main方法中调用fo
2022-09-10
剑道仙尊
33