Android进阶之路Android开发Android技术知识

Android 9.0 Launcher3源码分析(一)——系统

2019-05-10  本文已影响14人  当心你的背后

转载请注明原地址:https://www.jianshu.com/p/35e66fe56a58

现在网上能搜到的关于Android原生Launcher的一些文章,大多数是基于Android 7.0或者更早之前的,比较老旧。虽说依然可以作为参考,但是经过几个大版本的演进,还是多多少少有些不同的。于是打算自己写一写基于最新AOSP的Launcher3代码分析,供大家参考。

Android开机过程中,会把各种系统服务拉起,并且调用其systemReady()函数。其中最关键的ActivityManagerService拉起后,systemReady()中调用了一个函数startHomeActivityLocked()

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
...
    startHomeActivityLocked(currentUserId, "systemReady");
...
}

看一下这个函数

boolean startHomeActivityLocked(int userId, String reason) {
        if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
                && mTopAction == null) {
            // We are running in factory test mode, but unable to find
            // the factory test app, so just sit around displaying the
            // error message and don't try to start anything.
            return false;
        }
        Intent intent = getHomeIntent();
        ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
        if (aInfo != null) {
            intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
            // Don't do this if the home app is currently being
            // instrumented.
            aInfo = new ActivityInfo(aInfo);
            aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
            ProcessRecord app = getProcessRecordLocked(aInfo.processName,
                    aInfo.applicationInfo.uid, true);
            if (app == null || app.instr == null) {
                intent.setFlags(intent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
                final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
                // For ANR debugging to verify if the user activity is the one that actually
                // launched.
                final String myReason = reason + ":" + userId + ":" + resolvedUserId;
                mActivityStartController.startHomeActivity(intent, aInfo, myReason);
            }
        } else {
            Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
        }

        return true;
    }

这里会首先构造一个带有HOME category的Intent,用此intent来从PackageManagerService查询对应的ActivityInfo。

Intent getHomeIntent() {
        Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
        intent.setComponent(mTopComponent);
        intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
        if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
            intent.addCategory(Intent.CATEGORY_HOME);
        }
        return intent;
    }

这其中的mTopAction和mTopComponent,在工厂模式(不是设计模式的那个,而是前面代码里的factory test mode,应该是用于工厂生产使用的)下会被指定为其他内容,这个我们不需要关心。普通情况下就是ACTION_MAIN和null。那么category指定为CATEGORY_HOME后,查询的就是在Manifest中声明了该category的应用了。而系统的Launcher3应用就是在Manifest中声明了CATEGORY_HOME的,那么是不是这样一来就可以拉起Launcher了呢?没那么简单,这中间还有一点弯弯绕绕。

搜索系统源码,可以发现Settings中有一个Activity同样声明了CATEGORY_HOME,即FallbackHome(其实还有另外一个,不过正常启动系统是不会出现的)。如果把锁屏方式设置为无,重启之后可能是可以先看到一个“android正在启动”的页面,然后才真正出现了Launcher。那既然有两个声明了CATEGORY_HOME的页面,为什么不是开机后出现一个选择框让用户选择启动哪个呢?

我们知道Android 7.0之后增加了一个DirectBoot模式,详见https://developer.android.google.cn/training/articles/direct-boot.html?hl=zh-cn

对比两个应用,Settings是在Manifest中声明了android:directBootAware="true",而Launcher没有,所以在此情况下,因此刚开机时,其实只有FallbackHome这个页面会被检索到,也就不会出现应用选择的对话框了。然后FallbackHome这个界面会一直检测当前是否已经具备唤醒正常Launcher的条件,如果OK,就finish掉自己。见下面这段代码(来自FallbackHome.java)

private void maybeFinish() {
        if (getSystemService(UserManager.class).isUserUnlocked()) {
            final Intent homeIntent = new Intent(Intent.ACTION_MAIN)
                    .addCategory(Intent.CATEGORY_HOME);
            final ResolveInfo homeInfo = getPackageManager().resolveActivity(homeIntent, 0);
            if (Objects.equals(getPackageName(), homeInfo.activityInfo.packageName)) {
                if (UserManager.isSplitSystemUser()
                        && UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
                    // This avoids the situation where the system user has no home activity after
                    // SUW and this activity continues to throw out warnings. See b/28870689.
                    return;
                }
                Log.d(TAG, "User unlocked but no home; let's hope someone enables one soon?");
                mHandler.sendEmptyMessageDelayed(0, 500);
            } else {
                Log.d(TAG, "User unlocked and real home found; let's go!");
                getSystemService(PowerManager.class).userActivity(
                        SystemClock.uptimeMillis(), false);
                finish();
            }
        }
    }

finish之后系统会再次调用到AMS的startHomeActivityLocked,这时候就已经可以查询到两个声明CATEGORY_HOME的activity了。但此时依然不会有应用选择对话框。这是因为FallbackHome在manifest中声明了自己的优先级为-1000,PackageManagerService里面对这样的情况是做了处理的。我们可以看一下PMS里的resolveIntent来检索符合CATEGORY_HOME条件的应用时执行的逻辑逻辑。resolveIntent会调用到resolveIntentInternal

private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
        try {
            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");

            if (!sUserManager.exists(userId)) return null;
            final int callingUid = Binder.getCallingUid();
            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");

            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);

            final ResolveInfo bestChoice =
                    chooseBestActivity(intent, resolvedType, flags, query, userId);
            return bestChoice;
        } finally {
            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
        }
    }

resolveIntentInternal中,query这个List就是符合查询条件的所有组件,在此场景下也就是FallbackHome与Launcher3两个应用Activity了。然后在chooseBestActivity中,当出现一些优先级不同的情况时,系统会返回query List中的第一个元素(第一个元素在此情况下就是Launcher3的Activity,有兴趣的读者可以看下PMS的mResolvePrioritySorter,这里说明了返回List的排序规则)。

private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
            int flags, List<ResolveInfo> query, int userId) {
        ...
            } else if (N > 1) {
                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
                // If there is more than one activity with the same priority,
                // then let the user decide between them.
                ResolveInfo r0 = query.get(0);
                ResolveInfo r1 = query.get(1);
                if (DEBUG_INTENT_MATCHING || debug) {
                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
                            + r1.activityInfo.name + "=" + r1.priority);
                }
                // If the first activity has a higher priority, or a different
                // default, then it is always desirable to pick it.
                if (r0.priority != r1.priority
                        || r0.preferredOrder != r1.preferredOrder
                        || r0.isDefault != r1.isDefault) {
                    return query.get(0);
                }
        ...
}

这里进行另一个实践,把FallbackHome在Manifest中声明的priority去除,使其与Launcher3同等优先级,然后重启。这下就会出现应用选择对话框了。

于是经过前面所述的逻辑后,系统桌面Launcher3就正式登场了。下一篇将分析Launcher3的启动流程。

上一篇下一篇

猜你喜欢

热点阅读