Android FrameWork AMS+WMS+PMS详解(下)

上一章节讲述了 SystemServer进程中 SystemServer类中 做了几件核心的功能

 

<1> 创建系统上下文对象(其实是创建了ActivityThread类)。

<2> 创建SystemServiceManager对象。使用该对象 创建下面的 AMS。

<3> 创建ActivityManagerService对象。

<4> 创建PackageManagerService对象。

<5> 创建WindowManagerService对象。
 

 

详情:https://blog.csdn.net/weixin_37730482/article/details/72897106

 

本章节重点讲解 ActivityManagerService  PackageManagerService  WindowManagerService。

 

 

 

一.ActivityManagerService详解

 

ActivityManagerService类systemReady方法部分源码

package com.android.server.am;

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {


  ...

  startHomeActivityLocked(currentUserId, "systemReady");
 
  ...

}



核心代码执行startHomeActivityLocked方法。

 

startHomeActivityLocked方法源码

boolean startHomeActivityLocked(int userId, String reason) {
    

    //核心代码1 获取Intent对象
    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;


            //核心代码2 调用ActivityStartController类的startHomeActivity方法
            mActivityStartController.startHomeActivity(intent, aInfo, myReason);
        }
    } else {
         Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
     }

     return true;
}

由此可见,startHomeActivityLocked方法有两个核心功能。

 

获取Intent对象:getHomeIntent()方法源码

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

其中两个操作值的我们格外关注一下。

<1> mTopAction字段

//ActivityManagerService类的全局变量
String mTopAction = Intent.ACTION_MAIN;


//Intent.ACTION_MAIN:实际内容
@SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
public static final String ACTION_MAIN = "android.intent.action.MAIN";

 

<2> addCategory操作

intent.addCategory(Intent.CATEGORY_HOME);


//Intent.CATEGORY_HOME实际内容
@SdkConstant(SdkConstantType.INTENT_CATEGORY)
public static final String CATEGORY_HOME = "android.intent.category.HOME";

也就是说,getHomeIntent()方法在生成Intent对象时。

<1> 添加了Actionandroid.intent.action.MAIN的Action。主Activity。

<2> 添加了Categoryandroid.intent.category.HOME的Category。桌面程序打开。

 

 

调用ActivityStartController类的startHomeActivity方法

ActivityStartController类startHomeActivity方法源码

void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason) {
    mSupervisor.moveHomeStackTaskToTop(reason);

    mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
            .setOutActivity(tmpOutRecord)
            .setCallingUid(0)
            .setActivityInfo(aInfo)
            .execute();
    mLastHomeActivityStartRecord = tmpOutRecord[0];
    if (mSupervisor.inResumeTopActivity) {
        // If we are in resume section already, home activity will be initialized, but not
        // resumed (to avoid recursive resume) and will stay that way until something pokes it
        // again. We need to schedule another resume.
        mSupervisor.scheduleResumeTopActivities();
    }
}

核心功能:最终调用ActivityStarter类的startActivity方法。

 

ActivityStarter类的startActivity方法源码

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
    int result = START_CANCELED;
    try {
        mService.mWindowManager.deferSurfaceLayout();
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, outActivity);
    } finally {
        // If we are not able to proceed, disassociate the activity from the task. Leaving an
        // activity in an incomplete state can lead to issues, such as performing operations
        // without a window container.
        final ActivityStack stack = mStartActivity.getStack();
        if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
            stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
                    null /* intentResultData */, "startActivity", true /* oomAdj */);
        }
        mService.mWindowManager.continueSurfaceLayout();
    }

    postStartActivityProcessing(r, result, mTargetStack);

    return result;
}

 

ActivityStarter类的postStartActivityProcessing方法源码

void postStartActivityProcessing(ActivityRecord r, int result, ActivityStack targetStack) {
    if (ActivityManager.isStartResultFatalError(result)) {
        return;
    }

    // We're waiting for an activity launch to finish, but that activity simply
    // brought another activity to front. We must also handle the case where the task is already
    // in the front as a result of the trampoline activity being in the same task (it will be
    // considered focused as the trampoline will be finished). Let startActivityMayWait() know
    // about this, so it waits for the new activity to become visible instead.
    mSupervisor.reportWaitingActivityLaunchedIfNeeded(r, result);

    ActivityStack startedActivityStack = null;
    final ActivityStack currentStack = r.getStack();
    if (currentStack != null) {
        startedActivityStack = currentStack;
    } else if (mTargetStack != null) {
        startedActivityStack = targetStack;
    }

    if (startedActivityStack == null) {
        return;
    }

    final int clearTaskFlags = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK;
    boolean clearedTask = (mLaunchFlags & clearTaskFlags) == clearTaskFlags
            && mReuseTask != null;
    if (result == START_TASK_TO_FRONT || result == START_DELIVERED_TO_TOP || clearedTask) {
        // The activity was already running so it wasn't started, but either brought to the
        // front or the new intent was delivered to it since it was already in front. Notify
        // anyone interested in this piece of information.
        switch (startedActivityStack.getWindowingMode()) {
            case WINDOWING_MODE_PINNED:
                    mService.mTaskChangeNotificationController.notifyPinnedActivityRestartAttempt(
                        clearedTask);
                break;
            case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
                final ActivityStack homeStack = mSupervisor.mHomeStack;
                if (homeStack != null && homeStack.shouldBeVisible(null /* starting */)) {
                     mService.mWindowManager.showRecentApps();
                }
                break;
        }
    }
}

 

 

小结1

AMS(ActivityManagerService)服务启动Launcher桌面。

 

 

 

 

 

 

二.PackageManagerService详解

 

PackageManagerService类的main方法源码

package com.android.server.pm;


public static PackageManagerService main(Context context, Installer installer,
        boolean factoryTest, boolean onlyCore) {
    // Self-check for initial settings.

    PackageManagerServiceCompilerMapping.checkProperties();

    //核心代码1 创建PackageManagerService对象
    PackageManagerService m = new PackageManagerService(context, installer,
            factoryTest, onlyCore);
    m.enableSystemUserPackages();


    //核心代码2 使用ServiceManager注册“package”的服务
    ServiceManager.addService("package", m);
    final PackageManagerNative pmn = m.new PackageManagerNative();

    //核心代码3 使用ServiceManager注册“package_native”的服务
    ServiceManager.addService("package_native", pmn);
    return m;
}

可见,main方法核心功能有两个。

<1> 创建PackageManagerService对象。

<2> 使用ServiceManager对象注册两个服务 “package”和“package_native”。

 

 

PackageManagerService类的systemReady方法源码

@Override
public void systemReady() {
    enforceSystemOrRoot("Only the system can claim the system is ready");

    mSystemReady = true;
    final ContentResolver resolver = mContext.getContentResolver();
    ContentObserver co = new ContentObserver(mHandler) {
        @Override
        public void onChange(boolean selfChange) {
            mWebInstantAppsDisabled =
                    (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
                            (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
        }
    };
        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
                    .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
            false, co, UserHandle.USER_SYSTEM);
        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
                    .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
        co.onChange(true);

    // Disable any carrier apps. We do this very early in boot to prevent the apps from being
    // disabled after already being started.
    CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
            mContext.getContentResolver(), UserHandle.USER_SYSTEM);

    // Read the compatibilty setting when the system is ready.
    boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
            mContext.getContentResolver(),
            android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
    PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
    if (DEBUG_SETTINGS) {
        Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
    }

    int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;

    synchronized (mPackages) {
        // Verify that all of the preferred activity components actually
        // exist.  It is possible for applications to be updated and at
        // that point remove a previously declared activity component that
        // had been set as a preferred activity.  We try to clean this up
        // the next time we encounter that preferred activity, but it is
        // possible for the user flow to never be able to return to that
        // situation so here we do a sanity check to make sure we haven't
        // left any junk around.
        ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
            removed.clear();
            for (PreferredActivity pa : pir.filterSet()) {
                if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
                    removed.add(pa);
                }
            }
            if (removed.size() > 0) {
                for (int r=0; r<removed.size(); r++) {
                    PreferredActivity pa = removed.get(r);
                    Slog.w(TAG, "Removing dangling preferred activity: "
                                + pa.mPref.mComponent);
                    pir.removeFilter(pa);
                }
                mSettings.writePackageRestrictionsLPr(
                        mSettings.mPreferredActivities.keyAt(i));
            }
        }

        for (int userId : UserManagerService.getInstance().getUserIds()) {
            if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
                grantPermissionsUserIds = ArrayUtils.appendInt(
                        grantPermissionsUserIds, userId);
            }
        }
    }
    sUserManager.systemReady();
    // If we upgraded grant all default permissions before kicking off.
    for (int userId : grantPermissionsUserIds) {
        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
    }

    if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
        // If we did not grant default permissions, we preload from this the
        // default permission exceptions lazily to ensure we don't hit the
        // disk on a new user creation.
        mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
    }

    // Now that we've scanned all packages, and granted any default
    // permissions, ensure permissions are updated. Beware of dragons if you
    // try optimizing this.
    synchronized (mPackages) {
        mPermissionManager.updateAllPermissions(
                StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
                mPermissionCallback);
    }

    // Kick off any messages waiting for system ready
    if (mPostSystemReadyMessages != null) {
        for (Message msg : mPostSystemReadyMessages) {
            msg.sendToTarget();
        }
        mPostSystemReadyMessages = null;
    }

    // Watch for external volumes that come and go over time
    final StorageManager storage = mContext.getSystemService(StorageManager.class);
    storage.registerListener(mStorageListener);

    mInstallerService.systemReady();
    mDexManager.systemReady();
    mPackageDexOptimizer.systemReady();

    StorageManagerInternal StorageManagerInternal = LocalServices.getService(
            StorageManagerInternal.class);
    StorageManagerInternal.addExternalStoragePolicy(
            new StorageManagerInternal.ExternalStorageMountPolicy() {
         @Override
         public int getMountMode(int uid, String packageName) {
            if (Process.isIsolated(uid)) {
                return Zygote.MOUNT_EXTERNAL_NONE;
            }
            if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
                return Zygote.MOUNT_EXTERNAL_DEFAULT;
            }
            if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
                return Zygote.MOUNT_EXTERNAL_READ;
            }
            return Zygote.MOUNT_EXTERNAL_WRITE;
        }

        @Override
        public boolean hasExternalStorage(int uid, String packageName) {
            return true;
        }
    });

    // Now that we're mostly running, clean up stale users and apps
    sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
    reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);

    mPermissionManager.systemReady();

    if (mInstantAppResolverConnection != null) {
        mContext.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                mInstantAppResolverConnection.optimisticBind();
                mContext.unregisterReceiver(this);
            }
        }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
    }
}

可见,systemReady方法代码比较多。主要的核心功能有两个。

<1> 监听ContentResolver。

<2> 注册类型是android.intent.action.BOOT_COMPLETED的动态广播。

 

 

 

 

 

 

 

三.WindowManagerService详解

 

WindowManagerService类main方法源码

package com.android.server.wm;



public static WindowManagerService main(final Context context, final InputManagerService im,
        final boolean haveInputMethods, final boolean showBootMsgs, final boolean onlyCore,
        WindowManagerPolicy policy) {
    DisplayThread.getHandler().runWithScissors(() ->
            sInstance = new WindowManagerService(context, im, haveInputMethods, showBootMsgs,onlyCore, policy), 0);
    return sInstance;
}

 

WindowManagerService类systemReady方法源码

public void systemReady() {
    mPolicy.systemReady();
    mTaskSnapshotController.systemReady();
    mHasWideColorGamutSupport = queryWideColorGamutSupport();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值