安卓源码分析-Launcher请求到根Activity启动

幸越泽
2023-12-01

安卓源码分析-Launcher请求到Activity启动

本文基于刘望舒大佬著作《Android进阶解密》结合最新源码整理,丰富而成。内部包含我个人的理解,可能有误

本文基于安卓源码版本9.0.0_r3


Launcher(所谓的桌面)。但我们点击桌面上的图标后,launcher会调用
startActivitySafely请求Ams来启动该应用程序。在launcher的 startActivitySafely方法中,调用了父类BaseDraggingActivity的方法 startActivitySafely

/packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java
151    public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
152        if (mIsSafeModeEnabled && !Utilities.isSystemApp(this, intent)) {
153            Toast.makeText(this, R.string.safemode_shortcut_error, Toast.LENGTH_SHORT).show();
154            return false;
155        }
156
157        // Only launch using the new animation if the shortcut has not opted out (this is a
158        // private contract between launcher and may be ignored in the future).
159        boolean useLaunchAnimation = (v != null) &&
160                !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
161        Bundle optsBundle = useLaunchAnimation
162                ? getActivityLaunchOptionsAsBundle(v)
163                : null;
164
165        UserHandle user = item == null ? null : item.user;
166
167        // 向intent中添加FLAG_ACTIVITY_NEW_TASK会使根Activity在新的任务栈中启动
168        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
169        if (v != null) {
170            intent.setSourceBounds(getViewBounds(v));
171        }
172        try {
173            boolean isShortcut = Utilities.ATLEAST_MARSHMALLOW
174                    && (item instanceof ShortcutInfo)
175                    && (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
176                    || item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
177                    && !((ShortcutInfo) item).isPromise();
178            if (isShortcut) {
179                // Shortcuts need some special checks due to legacy reasons.
180                startShortcutIntentSafely(intent, optsBundle, item);
181            } else if (user == null || user.equals(Process.myUserHandle())) {
182                // 重点
183                startActivity(intent, optsBundle);
184            } else {
185                LauncherAppsCompat.getInstance(this).startActivityForProfile(
186                        intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
187            }
188            getUserEventDispatcher().logAppLaunch(v, intent);
189            return true;
190        } catch (ActivityNotFoundException|SecurityException e) {
191            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
192            Log.e(TAG, "Unable to launch. tag=" + item + " intent=" + intent, e);
193        }
194        return false;
195    }

在183调用关键方法startActivity继续跟踪。

/frameworks/base/core/java/android/app/Activity.java
4898    @Override
4899    public void startActivity(Intent intent, @Nullable Bundle options) {
4900        if (options != null) {
4901            startActivityForResult(intent, -1, options);
4902        } else {
4903            // Note we want to go through this call for compatibility with
4904            // applications that may have overridden the method.
4905            startActivityForResult(intent, -1);
4906        }
4907    }

继续调用startActivityForResult第二个参数表示需不需要知道启动结果。
由于目前介绍的是根Activty启动过程,所以在startActivityForResult里会调用 Instrumentation类的execStartActivity方法

/frameworks/base/core/java/android/app/Instrumentation.java
1844    public ActivityResult execStartActivity(
1845            Context who, IBinder contextThread, IBinder token, String resultWho,
1846            Intent intent, int requestCode, Bundle options, UserHandle user) {
......
1870        try {
1871            intent.migrateExtraStreamToClipData();
1872            intent.prepareToLeaveProcess(who);
1873            int result = ActivityManager.getService()
1874                .startActivityAsUser(whoThread, who.getBasePackageName(), intent,
1875                        intent.resolveTypeIfNeeded(who.getContentResolver()),
1876                        token, resultWho,
1877                        requestCode, 0, null, options, user.getIdentifier());
1878            checkStartActivityResult(result, intent);
1879        } catch (RemoteException e) {
1880            throw new RuntimeException("Failure from system", e);
1881        }
1882        

首先在1873行调用ActivityManager的getService获取Ams的代理对象。然后调用其startActivityAsUser。传出了user.getIdentifier() 获取用户id,在后面判断权限。
startActivityAsUser内部直接返回了自己的startActivityAsUser方法。

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
5096    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
5097            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
5098            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
5099            boolean validateIncomingUser) {
5100        enforceNotIsolatedCaller("startActivity");
5101
5102        userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
5103                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
5104
5105        // TODO: Switch to user app stacks here.
5106        return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
5107                .setCaller(caller)
5108                .setCallingPackage(callingPackage)
5109                .setResolvedType(resolvedType)
5110                .setResultTo(resultTo)
5111                .setResultWho(resultWho)
5112                .setRequestCode(requestCode)
5113                .setStartFlags(startFlags)
5114                .setProfilerInfo(profilerInfo)
5115                .setActivityOptions(bOptions)
5116                .setMayWait(userId)
5117                .execute();
5118
5119    }

5100行检测进程是否被隔离,是就抛出异常。
5102行检查调用者是否有权限,没有权限抛出异常。
在5106行进入了ActivityStarter的execute方法这里的调用引用其他大佬文章:

这里关于ActivityStarter对象的获取,稍微展开一下,总的来说是通过工厂模式+对象池的复用

mActivityStartController.obtainStarter()调用工厂来获取ActivityStarter对象
 ActivityStarter obtainStarter(Intent intent, String reason) {
        //ActivityStarter:DefaultFactory静态内部类对象
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }

这里的mFactoty对象是ActivityStarter的静态内部类DefaultFacory的实例,这个类定义了ActivityStarter的最大实例数和复用的对象池。

static class DefaultFactory implements Factory {
   private final int MAX_STARTER_COUNT = 3;
   ......
   private SynchronizedPool<ActivityStarter> mStarterPool =
                new SynchronizedPool<>(MAX_STARTER_COUNT);
  @Override
   public ActivityStarter obtain() {
       ActivityStarter starter = mStarterPool.acquire();
            if (starter == null) {
                starter = new ActivityStarter(mController, mService, mSupervisor, 
                mInterceptor);
            }
            return starter;     
    }
   @Override
        public void recycle(ActivityStarter starter) {
            //重置mRequest对象
            starter.reset(true /* clearRequest*/);
            mStarterPool.release(starter);
        }
}

这里可以看到,ActivityStarter的实例数最多不超过三个,是从对象池中获取的,并且每个放入池中的ActivityStarter对象都要进行reset重置清空操作。 在获取到ActivityStarter对象之后,再通过一系列的setXX方法,对mRequest的参数进行重新赋值,最后执行ActivityStarter:execute()方法。 ———————————————— ———————————————— ————————————
版权声明:本文为CSDN博主「满月丸子」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/onlymoon_gy/article/details/105404991

/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.j
ava
481    int execute() {
482        try {
483            // TODO(b/64750076): Look into passing request directly to these methods to allow
484            // for transactional diffs and preprocessing.
485            if (mRequest.mayWait) {
486                return startActivityMayWait(mRequest.caller, mRequest.callingUid,
487                        mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
488                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
489                        mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
490                        mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
491                        mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
492                        mRequest.inTask, mRequest.reason,
493                        mRequest.allowPendingRemoteAnimationRegistryLookup);
494            } else {
495                return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
496                        mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
497                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
498                        mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
499                        mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
500                        mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
501                        mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
502                        mRequest.outActivity, mRequest.inTask, mRequest.reason,
503                        mRequest.allowPendingRemoteAnimationRegistryLookup);
504            }
505        } finally {
506            onExecutionComplete();
507        }
508    }

因为在ActivityManagerService.startActivityAsUser中调用了ActivityStarter.setMayWait方法,所以这里 mRequest.mayWait值为true,会去调用startActivityMayWait方法。

945    private int startActivityMayWait(IApplicationThread caller, int callingUid,
946            String callingPackage, Intent intent, String resolvedType,
947            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
948            IBinder resultTo, String resultWho, int requestCode, int startFlags,
949            ProfilerInfo profilerInfo, WaitResult outResult,
950            Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
951            int userId, TaskRecord inTask, String reason,
952            boolean allowPendingRemoteAnimationRegistryLookup) {
......          
1099 int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
1100                    voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
1101                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
1102                    ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
1103                    allowPendingRemoteAnimationRegistryLookup);
1104
1105            Binder.restoreCallingIdentity(origId);
1106
.......
1170
1171            mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
1172            return res;
1173        }
1174    }

1099行调用startActivity方法内部重要的是给启动理由做了次判空,如果为空就抛出异常。
方法内部继续调用本地方法startActivity

/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
571    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
572            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
573            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
574            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
575            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
576            SafeActivityOptions options,
577            boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
578            TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
.......  
585        if (caller != null) {
586            callerApp = mService.getRecordForAppLocked(caller);
587            if (callerApp != null) {
588                callingPid = callerApp.pid;
589                callingUid = callerApp.info.uid;
590            } else {
591                Slog.w(TAG, "Unable to find app for caller " + caller
592                        + " (pid=" + callingPid + ") when starting: "
593                        + intent.toString());
594                err = ActivityManager.START_PERMISSION_DENIED;
595            }
596        }
.......
826        ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
827                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
828                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
829                mSupervisor, checkedOptions, sourceRecord);
830        if (outActivity != null) {
831            outActivity[0] = r;
832        }
.......
868        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
869                true /* doResume */, checkedOptions, inTask, outActivity);
870    }

585行判断caller是否为空,caller是一路传过来的,指向Launcher所在进程ApplicationThread对象。586行获取代表Launcher的callerApp对象,他的类型是ProcessRecord的

ProcessRecord类,用来描述一个应用程序进程

ActivtyRecord类,用来记录一个activty的所有信息

在826行给ActivtyRecord赋值。
最后调用startActivity传入了之前说的在数组outActivity第一位的ActivityRecord
startActivity重又调用了startActivityUnchecked方法

/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
1220    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
1221            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1222            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
1223            ActivityRecord[] outActivity) {
14
.....
1407        int result = START_SUCCESS;
1408        if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
1409                && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
1410            newTask = true;
1411            result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
1412        } else if (mSourceRecord != null) {
1413            result = setTaskFromSourceRecord();
1414        } else if (mInTask != null) {
1415            result = setTaskFromInTask();
1416        } else {
1417            // This not being started from an existing activity, and not part of a new task...
1418            // just put it in the top task, though these days this case should never happen.
1419            setTaskToCurrentTopOrCreateNewTask();
1420        }
......
1466                mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
1467                        mOptions);

startActivityUnchecked方法主要处理与栈管理的逻辑
1408行的判断中,判断了我们在之前在/packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java传入的intent。
在代码168行intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);我们给intent传入了。
在1411行处创建了一个新的TaskRecord,用来描述一个Activty任务栈,Activty任务栈只是一个模型,并不存在。1466行调用关键代码,继续跟踪

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
2214    boolean resumeFocusedStackTopActivityLocked(
2215            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
2216
2217        if (!readyToResume()) {
2218            return false;
2219        }
2220
2221        if (targetStack != null && isFocusedStack(targetStack)) {
2222            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
2223        }
2224
2225        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2226        if (r == null || !r.isState(RESUMED)) {
2227            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
2228        } else if (r.isState(RESUMED)) {
2229            // Kick off any lingering app transitions form the MoveTaskToFront operation.
2230            mFocusedStack.executeAppTransition(targetOptions);
2231        }
2232
2233        return false;
2234    }

2225行获取要启动的Activty所在栈的栈顶ActivtyRecord,要求不是处于停止状态
2226行判断栈顶是不是为空或者是RESUMED状态。,对于在启动的Activity来说,这个条件显然满足。所以执行resumeTopActivityUncheckedLocked
然后就是一连串调用,不重要就省略了
resumeTopActivityUncheckedLocked——》resumeTopActivityInnerLocked——》startSpecificActivityLocked方法

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
1678    void startSpecificActivityLocked(ActivityRecord r,
1679            boolean andResume, boolean checkConfig) {
1680        // Is this activity's application already running?
1681        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1682                r.info.applicationInfo.uid, true);
1683
1684        getLaunchTimeTracker().setLaunchTime(r);
1685
1686        if (app != null && app.thread != null) {
1687            try {
1688                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1689                        || !"android".equals(r.info.packageName)) {
1690                    // Don't add this if it is a platform component that is marked
1691                    // to run in multiple processes, because this is actually
1692                    // part of the framework so doesn't make sense to track as a
1693                    // separate apk in the process.
1694                    app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
1695                            mService.mProcessStats);
1696                }
1697                realStartActivityLocked(r, app, andResume, checkConfig);
1698                return;
1699            } catch (RemoteException e) {
1700                Slog.w(TAG, "Exception when starting activity "
1701                        + r.intent.getComponent().flattenToShortString(), e);
1702            }
1703
1704            // If a dead object exception was thrown -- fall through to
1705            // restart the application.
1706        }
1707
1708        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
1709                "activity", r.intent.getComponent(), false, false, true);
1710    }

1681行获取要启动的Activty所在的应用程序进程
1686行判断应用程序进程是否启动,如果没有启动将执行startProcessLocked方法
先启动应用程序进程,具体可以看我另一篇文章。
我们以启动了的逻辑走,将调用realStartActivityLocked方法
下面引用大佬文章:

跟进realStartActivityLocked方法

 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
            ...           

            try {
                ...

                // 这里传入的app.thread会赋值给ClientTransaction的成员变量mClient,
                // 而ClientTransaction会调用mClient.scheduleTransaction(this)来执行事务
                // 所以事务最终是调用app.thread的scheduleTransaction执行。
                // 而这个app.thread是ActivityThread的内部类ApplicationThread。
                final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                        r.appToken);
                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                        System.identityHashCode(r), r.info,
                        // TODO: Have this take the merged configuration instead of separate global
                        // and override configs.
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                        r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                        profilerInfo));

                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // Schedule transaction.
                // ---------看这里---------
                // 执行Activity启动事务
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
                ...
            } catch (RemoteException e) {
                if (r.launchFailed) {
                    // 第二次启动失败的异常处理
                    return false;
                }

                // 第一次启动失败,重试
                r.launchFailed = true;
                app.activities.remove(r);
                throw e;
            }
        } finally {
            endDeferResume();
        }
        ...
        return true;
    }

在realStartActivityLocked中最主要的工作就是创建了Activity的启动事务ClientTransaction,并调用ClientLifecycleManager的scheduleTransaction方法启动它。接下来,看ClientTransaction事务中是怎么启动Activity的。

路径:/frameworks/base/services/core/java/com/android/server/am/ClientLifecycleManager.java

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        
        // ---------看这里---------
        transaction.schedule();
        
        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();
        }
    }

调用ClientTransaction的schedule方法,继续跟进

public void schedule() throws RemoteException {
    mClient.scheduleTransaction(this);
}

这里调用了mClient的scheduleTransaction方法,这里的mClient是在创建ClientTransaction事务对象的时候赋值的,也就是调用obtain方法时。

路径:/frameworks/base/services/core/java/com/android/server/am/ClientLifecycleManager.java

    public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
        ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
        if (instance == null) {
            instance = new ClientTransaction();
        }
        instance.mClient = client;
        instance.mActivityToken = activityToken;

        return instance;
    }

好,回到ActivityStackSupervisor的realStartActivityLocked方法中,最终会调用mService.getLifecycleManager().scheduleTransaction(clientTransaction)启动Activity事务,可以看到,获取clientTransaction参数的obtain方法中,赋值给mClient的是app.thread,所以事务最终是调用的app.thread的scheduleTransaction方法来执行,而这个app.thread是ActivityThread的内部类ApplicationThread。所以流程转到了ActivityThread的内部类ApplicationThread中。

路径:/frameworks/base/core/java/android/app/ActivityThread.java
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction);
}

这里还是调用了ActivityThread的scheduleTransaction方法。但是ActivityThread类中并没有scheduleTransaction这个方法。因此自然会想到很可能是继承的父类中的方法。ActivityThread继承的是ClientTransactionHandler类,在ClientTransactionHandler类中发现了scheduleTransaction方法。所以这里最终调用的就是ClientTransactionHandler中的scheduleTransaction方法。

void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

这里调用了sendMessage方法,而sendMessage是一个抽象方法,所以这里调用的是ActivityThread类中的sendMessage实现。

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);
}

这里就是生成了一个Message对象,并向mH这个Handler发送一个what为ActivityThread.H.EXECUTE_TRANSACTION的消息。去查看Handler(ActivityThread.H)中对EXECUTE_TRANSACTION消息的处理。

case EXECUTE_TRANSACTION:
        final ClientTransaction transaction = (ClientTransaction) msg.obj;
        // ---------看这里---------
        // 调用TransactionExecutor的execute方法
        mTransactionExecutor.execute(transaction);
        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;

9、TransactionExecutor->execute
路径:/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor
这里调用了TransactionExecutor的execute方法

public void execute(ClientTransaction transaction) {
    final IBinder token = transaction.getActivityToken();
    log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);

    // ---------看这里---------
    executeCallbacks(transaction);
    executeLifecycleState(transaction);
    
    mPendingActions.clear();
    log("End resolving transaction");
}

这里调用了executeCallbacks和executeLifecycleState两个方法,查看两个方法就会发现,这两个方法最后都会调用cycleToPath这个方法。

private void cycleToPath(ActivityClientRecord r, int finish,
        boolean excludeLastState) {
    final int start = r.getLifecycleState();
    log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    // ---------看这里---------
    performLifecycleSequence(r, path);
}

继续看performLifecycleSequence方法

private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
    final int size = path.size();
    for (int i = 0, state; i < size; i++) {
        state = path.get(i);
        log("Transitioning to state: " + state);
        switch (state) {
            case ON_CREATE:
             // ---------看这里---------
             mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                        null /* customIntent */);
                break;
            case ON_START:
                mTransactionHandler.handleStartActivity(r, mPendingActions);
                break;
            case ON_RESUME:
                mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                        r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                break;
            case ON_PAUSE:
                mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                        false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                        "LIFECYCLER_PAUSE_ACTIVITY");
                break;
            case ON_STOP:
                mTransactionHandler.handleStopActivity(r.token, false /* show */,
                        0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
                        "LIFECYCLER_STOP_ACTIVITY");
                break;
            case ON_DESTROY:
                mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                        0 /* configChanges */, false /* getNonConfigInstance */,
                        "performLifecycleSequence. cycling to:" + path.get(size - 1));
                break;
            case ON_RESTART:
                mTransactionHandler.performRestartActivity(r.token, false /* start */);
                break;
            default:
                throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
        }
    }
}

可以看到,Activity的生命周期就是在这里进行一个相关方法的调用。
这里的成员变量mTransactionHandler是一个ClientTransactionHandler对象,在ClientTransactionHandler中这些方法都是抽象方法,这里执行的是ClientTransactionHandler的实现类ActivityThread中的handleLaunchActivity方法。

10、ActivityThread->handleLaunchActivity

路径:/frameworks/base/core/java/android/app/ActivityThread.java
public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
    // If we are getting ready to gc after going to the background, well
    // we are back active so skip it.
    unscheduleGcIdler();
    mSomeActivitiesChanged = true;

    if (r.profilerInfo != null) {
        mProfiler.setProfiler(r.profilerInfo);
        mProfiler.startProfiling();
    }

    // Make sure we are running with the most recent config.
    handleConfigurationChanged(null, null);

    if (localLOGV) Slog.v(
        TAG, "Handling launch of " + r);

    // Initialize before creating the activity
    if (!ThreadedRenderer.sRendererDisabled) {
        GraphicsEnvironment.earlyInitEGL();
    }
    //创建WindowManagerServer
    WindowManagerGlobal.initialize();

    // ---------看这里---------
    // 通过反射创建指定的Activity,并回调Activity的performCreate方法执行onCreate
    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 {
            ActivityManager.getService()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

    return a;
}

好,继续跟进performLaunchActivity方法

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

        // 获取要启动的Activity的ComponentName类,该类保存了Activity类名和包名
        ComponentName component = r.intent.getComponent();
        ...

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

        try {
            // 创建Application,makeApplication方法内部会调用创建Application的onCreate()
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            ...
            if (activity != null) {
                ...
                // 初始化Activity,在attach方法中会创建window对象并与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);
                }
               ...
            }
            ...
        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
            ...
        }

        return activity;
    }

这个方法中的注释已经很明确了,获取ActivityInfo、ComponentName、appContext,并创建了Application,回调Application的onCreate(),最后调用Instrumentation的callActivityOnCreate()方法来启动Activity
11、Instrumentation->callActivityOnCreate

路径:/frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle,
            PersistableBundle persistentState) {
        prePerformCreate(activity);
        // ---------看这里---------
        activity.performCreate(icicle, persistentState);
        postPerformCreate(activity);
    }

可以看到,最终是调用了Activity的performCreate()方法,继续跟进
12、Activity->performCreate

路径:/frameworks/base/core/java/android/app/Activity.java
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        mCanEnterPictureInPicture = true;
        restoreHasCurrentPermissionRequest(icicle);
        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());
    }

performCreate方法中调用了Acitivity的onCreate方法。到目前为止,我们分析了Launcher请求AMS、AMS到ApplicationThread的调用过程、ActivityThread启动Activity的过程,从根Activity的启动过程中可以看到,若我们想做启动耗时优化,目前最明显且易控制的方式就是尽量少在Application和Activity的onCreate()方法中做耗时操作,一些后面才会用到的库或者其他三方库可以延迟初始化。
————————————————
版权声明:本文为CSDN博主「JokerWann」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/isJoker/article/details/95523840
总结:
首先Launcher(桌面程序)进程向Ams请求创建根Activity。Ams内部会判断该应用程序进程是否已经启动,如果没有启动将会向Zygote请求创建应用程序进程。应用程序进程启动后Ams会请求创建根Activity。

 类似资料: