Systemui和Launcher是如何无限重启

systemui 死亡后从哪拉起

结论:进程死了 → appDiedLocked → cleanUpApplicationRecordLocked(AMS 第12346行),

persistent 分支(第12409/12421行)把 restart 置 true,第12445行 startProcessLocked

带 HostingRecord.HOSTING_TYPE_RESTART("restart") 直接拉起 → logcat 里是 "for restart"。

代码定位(frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java):

确认车机这台 systemui 是不是 persistent:

bash 复制代码
adb shell "dumpsys package com.android.systemui"

看历史/实时拉起记录(hosting type 就在这里):

bash 复制代码
adb shell killall com.android.systemui
adb shell "logcat -b all -d | grep -E 'Start proc [0-9]+:com.android.systemui'"
# 开机那次是 "for added application"(startPersistentApps → addAppLocked)
# 死亡重启会是 "for restart com.android.systemui"

日志对应代码

appDiedLocked 是被谁调用的

主路:binder 死亡回执(不是轮询 pid)

attachApplicationLocked 里给应用的 IApplicationThread binder 挂死亡回执:

AMS 第4728行 thread.asBinder().linkToDeath(adr, 0); app.setDeathRecipient(adr);

应用进程一死 → binder 驱动给 system_server 发 BR_DEAD_BINDER → binder 线程池回调

AMS 第1473行 AppDeathRecipient.binderDied() → synchronized(this){ appDiedLocked(mApp,mPid,mAppThread,true,null); }

注意:在 binder 线程上执行,所以要自己拿 AMS 锁。

验证(杀掉 systemui 看死亡日志;会闪黑屏,自己决定跑不跑):

bash 复制代码
adb shell "logcat -c; kill -9 \$(pidof com.android.systemui); sleep 3"
adb shell "logcat -d | grep -E 'has died|Spurious death|for restart'"
# 期望:Process com.android.systemui (pid xxxx) has died: pers ... 然后 Start proc ... for restart

日志对应代码

接下来看看launcher是怎么启动

SystemServer》systemReady

接下来各种ready

AMS>startHomeOnAllDisplays>ATMS>LocalServer(ATMS内部类)>RootWindowContainer(ATMS 内部成员)>

关键点

java 复制代码
 homeIntent = mService.getHomeIntent();
 aInfo = resolveHomeActivity(userId, homeIntent);

获取pms的binder,并查询mTopAction,aidl接口为resolvedType

final ResolveInfo info = AppGlobals.getPackageManager() .resolveIntent(homeIntent, resolvedType, flags, userId);

对应的实现类 你可以这么搜IPackageManager.Stub

我们就找到了IPackageManagerBase

bash 复制代码
String mTopAction = Intent.ACTION_MAIN;
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;
    }
    
   public static IPackageManager getPackageManager() {
        if (sPackageManager != null) {
            return sPackageManager;
        }
        final IBinder b = ServiceManager.getService("package");
        sPackageManager = IPackageManager.Stub.asInterface(b);
        return sPackageManager;
    }

直接找关键代码ComponentResolverBase 我理解是意图解析器

bash 复制代码
public abstract class ComponentResolverBase extends WatchableImpl implements ComponentResolverApi {

    @NonNull
    protected ComponentResolver.ActivityIntentResolver mActivities;

    @NonNull
    protected ComponentResolver.ProviderIntentResolver mProviders;

    @NonNull
    protected ComponentResolver.ReceiverIntentResolver mReceivers;

    @NonNull
    protected ComponentResolver.ServiceIntentResolver mServices;

最后总算是找到了ntentFilter.hasCategory(Intent.CATEGORY_DEFAULT)

经过了复杂的 pms查询过程,还是从RootWindowContanier中执行

java 复制代码
// Update the reason for ANR debugging to verify if the user activity is the one that
// actually launched.
final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(
aInfo.applicationInfo.uid) + ":" + taskDisplayArea.getDisplayId();
mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
taskDisplayArea);

在启动之前 还有一个选择的过程

即 ResolveIntentHelper.chooseBestActivity:150 决出唯一一个 → 返回 ATMS。

看注释一目了然,当然这个页面肯定也是基于此出现的结果

bash 复制代码
private ResolveInfo chooseBestActivity(Computer computer, Intent intent, String resolvedType,
            @PackageManager.ResolveInfoFlagsBits long flags,
            @PackageManagerInternal.PrivateResolveFlags long privateResolveFlags,
            List<ResolveInfo> query, int userId, boolean queryMayBeFiltered) {
        if (query != null) {
            final int n = query.size();
            if (n == 1) {
                return query.get(0);
            } 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);
                }
                // If we have saved a preference for a preferred activity for
                // this Intent, use that.
                ResolveInfo ri = mPreferredActivityHelper.findPreferredActivityNotLocked(computer,
                        intent, resolvedType, flags, query, true, false, debug,
                        userId, queryMayBeFiltered);
                if (ri != null) {
                    return ri;
                }
                int browserCount = 0;
                for (int i = 0; i < n; i++) {
                    ri = query.get(i);
                    if (ri.handleAllWebDataURI) {
                        browserCount++;
                    }
                    // If we have an ephemeral app, use it
                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
                        final String packageName = ri.activityInfo.packageName;
                        final PackageStateInternal ps =
                                computer.getPackageStateInternal(packageName);
                        if (ps != null && PackageManagerServiceUtils.hasAnyDomainApproval(
                                mDomainVerificationManager, ps, intent, flags, userId)) {
                            return ri;
                        }
                    }
                }
                if ((privateResolveFlags
                        & PackageManagerInternal.RESOLVE_NON_RESOLVER_ONLY) != 0) {
                    return null;
                }
                ri = new ResolveInfo(mResolveInfoSupplier.get());
                // if all resolve options are browsers, mark the resolver's info as if it were
                // also a browser.
                ri.handleAllWebDataURI = browserCount == n;
                ri.activityInfo = new ActivityInfo(ri.activityInfo);
                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
                // If all of the options come from the same package, show the application's
                // label and icon instead of the generic resolver's.
                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
                // and then throw away the ResolveInfo itself, meaning that the caller loses
                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
                // a fallback for this case; we only set the target package's resources on
                // the ResolveInfo, not the ActivityInfo.
                final String intentPackage = intent.getPackage();
                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
                    ri.resolvePackageName = intentPackage;
                    if (mUserNeedsBadging.get(userId)) {
                        ri.noResourceId = true;
                    } else {
                        ri.icon = appi.icon;
                    }
                    ri.iconResourceId = appi.icon;
                    ri.labelRes = appi.labelRes;
                }
                ri.activityInfo.applicationInfo = new ApplicationInfo(
                        ri.activityInfo.applicationInfo);
                if (userId != 0) {
                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
                }
                // Make sure that the resolver is displayable in car mode
                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
                return ri;
            }
        }
        return null;
    }
bash 复制代码
# 谁被解析为 home
adb shell cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME
# 去掉默认桌面(--user 不能放最后,RoleShellCommand 会把它当 flags 解析报 NumberFormatException;默认就是 user 10,直接省掉)
adb  shell cmd role clear-role-holders  --user 10  android.app.role.HOME

# 指定 com.xiaokj.systemui_test 为 home
adb  shell cmd package set-home-activity --user 10 com.xiaokj.systemui_test
adb  shell cmd package set-home-activity --user 10 com.android.car.carlauncher

# 它有没有 HOME 入口(没有 -c android.intent.category.HOME 就永远设不上)
adb  shell "dumpsys package com.xiaokj.systemui_test | grep -i HOME"

#  HOME role 现在归谁
adb  shell "dumpsys role | grep -i -A3 HOME"

# 模拟home键
adb shell input keyevent KEYCODE_HOME
# 获取当前用户
adb shell am get-current-user
# 获取用户
adb shell pm list users
bash 复制代码
adb root
adb shell stop
adb shell rm /data/system/users/10/package-restrictions.xml
adb shell start
adb shell cmd role clear-role-holders android.app.role.HOME --user 10
adb shell am start --user 10 -a android.intent.action.MAIN -c android.intent.category.HOME
最后的问题:launcher被kill和自动拉起来

直接给答案

简单点说就是又点了一下home键

bash 复制代码
    launcher 不在这个分支里(它不是 persistent),所以它"自己回来"这件事根本不是 AMS 干的,是另一条路:

      它当时正显示着被杀 → 这块屏 top activity 变 null
      → ActivityTaskSupervisor:1019 START_HOME_MSG
      → RootWindowContainer.startHomeOnEmptyDisplays:1391
      → 走 startHome 那条链冷启动一次

总结:他们两个都是走的AMS中的 binder死亡监听,systemui靠persistent复活进程,而launcher靠查询候选HOME从而复活

相关推荐
GY-935 小时前
【Android】WorkManager
android
fatiaozhang95277 小时前
开心电视助手极速版-版本9.6-新增安卓平台版本
android·开心电视助手极速版·版本9.6
urkay-8 小时前
Android 线程池工具类与监控
android·java·性能优化
StarsGreen8 小时前
Android 12 添加 v4l2_codec 服务详细流程
android
FungLeo9 小时前
FengCMS · PHP+MySQL升级实录 · 存量站升级方法论:备份 → 副本验收→migrate.php→ 停写切换
android·mysql·php·工程实践·fengcms
booboosui1 天前
清单 40 件是硬上限:过期的活挂了 48 小时才被打标记
android
FlightYe1 天前
linux系统编程(二十一):C 语言常见坑
android·linux·运维·服务器·c语言·音视频