ActivityManagerService启动Launcher过程详解——Android 12(四)

前边介绍了AMS和ATMS startService()的启动过程、setSystemProcess()阶段、installSystemProviders()阶段,本文介绍AMS.systemReady()的阶段,包含启动home activity的过程,home activity根据是否注册system uid来判断是启动Launch还是setup wizard。


目录

1 SystemServer.startOtherService()中的AMS.systemReady()

2. AMS.systemReady()

3. AMS启动Home Activity的过程

3.1 Provision的AndroidManifest.xml

 3.2 Launcher3的AndroidManifest.xml

 3.2 ActivityTaskManager.LocalService.startHomeOnAllDisplays()

3.2.1 ActivityTaskManagerService.LocalService. startHomeOnAllDisplays()

3.2.2 RootWindowContainer.startHomeOnAllDisplays()

3.2.3 RootWindowContainer.startHomeOnDisplay()。

3.2.4 RootWindowContainer.startHomeOnTaskDisplayArea()

3.2.5 ATMS.getHomeIntent()

3.2.6 RootWindowContainer.resolveHomeActivity()

3.2.7 ActivityStartController.startHomeActivity()

3.2.8 ActivityStarter.execute()

3.2.9 ActivityStarter.executeRequset()

3.2.10  ActivityStarter.startActivityUnchecked() 

3.2.11 ActivityStarter.startActivityInner() 

3.2.12 RootWindowContainer.resumeFocusedTasksTopActivities()  

3.2.13 Task.resumeFocusedTasksTopActivities()  

3.2.14 Task.resumeTopActivityInnerLocked()   

3.2.15 ActivityTaskSupervisor .startSpecificActivity()   


1 SystemServer.startOtherService()中的AMS.systemReady()

// /frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer implements Dumpable {
    private void startOtherServices(TimingsTraceAndSlog t) {
        //AMS.systemReady()
        mActivityManagerService.systemReady(() -> {
            //1. 回调各个系统Service的onBootPhase(), AMS ready.
            mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
            ...
            //2. 回调各个系统Service的onBootPhase(), 可以启动第三方应用
            mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
            ...            
        }, t);   
    }
}

2. AMS.systemReady()

它的第一个参数是Runnable,

参考代码地址:ActivityManagerService.java - OpenGrok cross reference for /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

代码非常负责,总结下主要工作:

  •  调用ATMS.onSystemmReady(),他内部通知一些服务ready。
  • AMS调用 mUserController、mAppOpsService、 mProcessList,回调他们的onSystemReady()
  •  kill已经启动的app, persistent=true的app可能先于AMS启动完成就启动
  •  执行SystemServer.startOtherServices()中调用AMS.systemReady()传递的参数
  • 启动各种Apps,启动包括persistent=true的app,home activity等。
//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
    volatile boolean mSystemReady = false;  
   public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
        t.traceBegin("PhaseActivityManagerReady");
        //从LocalServices中获取UserManagerInternal service
        mSystemServiceManager.preSystemReady();
        synchronized(this) {
            //第一次进来该flag=false
            if (mSystemReady) {
                //mSystemReady=true后,执行system server中的runnable,进入下个阶段
                if (goingCallback != null) {
                    goingCallback.run();
                }
                t.traceEnd(); // PhaseActivityManagerReady
                return;
            }

            t.traceBegin("controllersReady");
            //获取设备空闲和低耗电模式的service
            mLocalDeviceIdleController = LocalServices.getService(DeviceIdleInternal.class);
            // ATMS ready
            mActivityTaskManager.onSystemReady();
            // Make sure we have the current profile info, since it is needed for security checks.
            mUserController.onSystemReady();
            mAppOpsService.systemReady();
            mProcessList.onSystemReady();
            mSystemReady = true;
            t.traceEnd();
        }

        try {
            //获取设备标识,SN
            sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
                    ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
                    .getSerial();
        } catch (RemoteException e) {}

        t.traceBegin("killProcesses");
        //kill已经启动的app, persistent=true的app可能先于AMS启动完成就启动
        //把这些应用kill
        ArrayList<ProcessRecord> procsToKill = null;
        synchronized(mPidsSelfLocked) {
            for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
                ProcessRecord proc = mPidsSelfLocked.valueAt(i);
                if (!isAllowedWhileBooting(proc.info)){
                    if (procsToKill == null) {
                        procsToKill = new ArrayList<ProcessRecord>();
                    }
                    procsToKill.add(proc);
                }
            }
        }

        synchronized(this) {
            if (procsToKill != null) {
                for (int i = procsToKill.size() - 1; i >= 0; i--) {
                    ProcessRecord proc = procsToKill.get(i);
                    Slog.i(TAG, "Removing system update proc: " + proc);
                    mProcessList.removeProcessLocked(proc, true, false,
                            ApplicationExitInfo.REASON_OTHER,
                            ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE,
                            "system update done");
                }
            }

            // Now that we have cleaned up any update processes, we
            // are ready to start launching real processes and know that
            // we won't trample on them any more.
            mProcessesReady = true;
        }
        t.traceEnd(); // KillProcesses

        Slog.i(TAG, "System now ready");

        EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis());

        t.traceBegin("updateTopComponentForFactoryTest");
        mAtmInternal.updateTopComponentForFactoryTest();
        t.traceEnd();

        t.traceBegin("registerActivityLaunchObserver");
        mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
        t.traceEnd();

        t.traceBegin("watchDeviceProvisioning");
        watchDeviceProvisioning(mContext);
        t.traceEnd();

        t.traceBegin("retrieveSettings");
        retrieveSettings();
        t.traceEnd();

        t.traceBegin("Ugm.onSystemReady");
        mUgmInternal.onSystemReady();
        t.traceEnd();

        t.traceBegin("updateForceBackgroundCheck");
        final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
        if (pmi != null) {
            pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
                    state -> updateForceBackgroundCheck(state.batterySaverEnabled));
            updateForceBackgroundCheck(
                    pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
        } else {
            Slog.wtf(TAG, "PowerManagerInternal not found.");
        }
        t.traceEnd();
        //执行SystemServer.startOtherServices()中调用AMS.systemReady()传递的参数
        if (goingCallback != null) goingCallback.run();

        t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks
        // Check the current user here as a user can be started inside goingCallback.run() from
        // other system services.
        final int currentUserId = mUserController.getCurrentUserId();
        Slog.i(TAG, "Current user:" + currentUserId);
        if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
            // User other than system user has started. Make sure that system user is already
            // started before switching user.
            throw new RuntimeException("System user not started while current user is:"
                    + currentUserId);
        }
        t.traceEnd();

        t.traceBegin("ActivityManagerStartApps");
        mBatteryStatsService.onSystemReady();
        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
                Integer.toString(currentUserId), currentUserId);
        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
                Integer.toString(currentUserId), currentUserId);

        final boolean bootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;

        if (bootingSystemUser) {
            mSystemServiceManager.onUserStarting(t, currentUserId);
        }

        synchronized (this) {
            // Only start up encryption-aware persistent apps; once user is
            // unlocked we'll come back around and start unaware apps
            t.traceBegin("startPersistentApps");
            startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
            t.traceEnd();

            // Start up initial activity.
            mBooting = true;
            // 为system user启动home activity. 如果system user没有设置,由开机引导app来处理home activity.
            if (UserManager.isSplitSystemUser() &&
                    Settings.Secure.getInt(mContext.getContentResolver(),
                         Settings.Secure.USER_SETUP_COMPLETE, 0) != 0
                    || SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) {
                t.traceBegin("enableHomeActivity");
                ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
                try {
                    AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
                            UserHandle.USER_SYSTEM);
                } catch (RemoteException e) {
                    throw e.rethrowAsRuntimeException();
                }
                t.traceEnd();
            }

            if (bootingSystemUser) {
                t.traceBegin("startHomeOnAllDisplays");
                mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
                t.traceEnd();
            }

            t.traceBegin("showSystemReadyErrorDialogs");
            mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
            t.traceEnd();


            if (bootingSystemUser) {
                t.traceBegin("sendUserStartBroadcast");
                final int callingUid = Binder.getCallingUid();
                final int callingPid = Binder.getCallingPid();
                final long ident = Binder.clearCallingIdentity();
                try {
                    Intent intent = new Intent(Intent.ACTION_USER_STARTED);
                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
                            | Intent.FLAG_RECEIVER_FOREGROUND);
                    intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
                    broadcastIntentLocked(null, null, null, intent,
                            null, null, 0, null, null, null, null, OP_NONE,
                            null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
                            currentUserId);
                    intent = new Intent(Intent.ACTION_USER_STARTING);
                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
                    intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
                    broadcastIntentLocked(null, null, null, intent, null,
                            new IIntentReceiver.Stub() {
                                @Override
                                public void performReceive(Intent intent, int resultCode,
                                        String data, Bundle extras, boolean ordered, boolean sticky,
                                        int sendingUser) {}
                            }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, null, OP_NONE,
                            null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
                            UserHandle.USER_ALL);
                } catch (Throwable e) {
                    Slog.wtf(TAG, "Failed sending first user broadcasts", e);
                } finally {
                    Binder.restoreCallingIdentity(ident);
                }
                t.traceEnd();
            } else {
                Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
                        + currentUserId);
            }

            t.traceBegin("resumeTopActivities");
            mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
            t.traceEnd();

            if (bootingSystemUser) {
                t.traceBegin("sendUserSwitchBroadcasts");
                mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
                t.traceEnd();
            }

            t.traceBegin("setBinderProxies");
            BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
                    BINDER_PROXY_LOW_WATERMARK);
            BinderInternal.nSetBinderProxyCountEnabled(true);
            BinderInternal.setBinderProxyCountCallback(
                    (uid) -> {
                        Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
                                + Process.myUid());
                        BinderProxy.dumpProxyDebugInfo();
                        if (uid == Process.SYSTEM_UID) {
                            Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
                        } else {
                            killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
                                    "Too many Binders sent to SYSTEM");
                        }
                    }, mHandler);
            t.traceEnd(); // setBinderProxies

            t.traceEnd(); // ActivityManagerStartApps
            t.traceEnd(); // PhaseActivityManagerReady
        }
    }

由于AMS.systemReady()启动的很复杂,目前没有要详细追踪的类,只会沿着启动Launcher或者开机引导程序的线进行分析。


3. AMS启动Home Activity的过程

Android 12中set wizard的App是Provision,路径在:/packages/apps/Provison,代码路径为:Android.bp - OpenGrok cross reference for /packages/apps/Provision/Android.bp

 Launcher3和Provision的主Activity中的intent-filter,都包含action=MAIN,category=HOME and Default,这是AMS拉起Home activity的主要依据。

整个过程非常复杂,只把关键的类和方法列出时序,如下图所示:最后调用ActivityTaskSupervisor.startSpecificActivity()会去判断当前activity的进程是否启动,如果进程启动则会调用ActivityTaskSupervisor.realStartActivityLocked(),不存在则最终会调用AMS.startProcessAsync()。

3.1 Provision的AndroidManifest.xml

下边是Provision的AndroidManifest.xml中Activity的intent,请于后边Launcher3的AndroidManifest.xml对比看。

 

 Setup wizard app只有一个DefaultActivity,启动完成后会设置Provision state,而且还会把自己从package manger中remove并finish该Activity。

// /packages/apps/Provision/src/com/android/provision/DefaultActivity.java
public class DefaultActivity extends Activity {
        @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        boolean provisionDeviceOwner = getSettings(getContentResolver(), SETTINGS_PROVISION_DO_MODE,
                DEFAULT_SETTINGS_PROVISION_DO_MODE) == 1;

        if (provisionDeviceOwner) {
            provisionDeviceOwner();
            return;
        }
        finishSetup();
    }

    private void finishSetup() {
        setProvisioningState();
        disableSelfAndFinish();
    }

    private void setProvisioningState() {
        Log.i(TAG, "Setting provisioning state");
        // Add a persistent setting to allow other apps to know the device has been provisioned.
        Settings.Global.putInt(getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 1);
        Settings.Secure.putInt(getContentResolver(), Settings.Secure.USER_SETUP_COMPLETE, 1);
    }

    private void disableSelfAndFinish() {
        // remove this activity from the package manager.
        PackageManager pm = getPackageManager();
        ComponentName name = new ComponentName(this, DefaultActivity.class);
        Log.i(TAG, "Disabling itself (" + name + ")");
        pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        // terminate the activity.
        finish();
    }
}

 3.2 Launcher3的AndroidManifest.xml

 3.2 ActivityTaskManager.LocalService.startHomeOnAllDisplays()

 ActivityManagerService.systemReady()中启动Home Activity的过程。

public ActivityTaskManagerInternal mAtmInternal;
public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
    ...    
    if (bootingSystemUser) {
        t.traceBegin("startHomeOnAllDisplays");
        mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
        t.traceEnd();
    }
    ...
}

3.2.1 ActivityTaskManagerService.LocalService. startHomeOnAllDisplays()

RootWindowContainer mRootWindowContainer;
@Override
public boolean startHomeOnAllDisplays(int userId, String reason) {
    synchronized (mGlobalLock) {
        return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
    }
}

3.2.2 RootWindowContainer.startHomeOnAllDisplays()

 在该方法中遍历所有child的display,对每一个displayId调用startHomeOnDisplay()。代码路径为:RootWindowContainer.java - OpenGrok cross reference for /frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java

class RootWindowContainer extends WindowContainer<DisplayContent>
        implements DisplayManager.DisplayListener {

    boolean startHomeOnAllDisplays(int userId, String reason) {
        boolean homeStarted = false;
        for (int i = getChildCount() - 1; i >= 0; i--) {
            final int displayId = getChildAt(i).mDisplayId;
            homeStarted |= startHomeOnDisplay(userId, reason, displayId);
        }
        return homeStarted;
    }
}

3.2.3 RootWindowContainer.startHomeOnDisplay()。

class RootWindowContainer extends WindowContainer<DisplayContent>
        implements DisplayManager.DisplayListener {

        boolean startHomeOnDisplay(int userId, String reason, int displayId) {
        return startHomeOnDisplay(userId, reason, displayId, false /* allowInstrumenting */,
                false /* fromHomeKey */);
    }

    boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,
            boolean fromHomeKey) {
        // Fallback to top focused display or default display if the displayId is invalid.
        if (displayId == INVALID_DISPLAY) {
            final Task rootTask = getTopDisplayFocusedRootTask();
            displayId = rootTask != null ? rootTask.getDisplayId() : DEFAULT_DISPLAY;
        }

        final DisplayContent display = getDisplayContent(displayId);
        return display.reduceOnAllTaskDisplayAreas((taskDisplayArea, result) ->
                        result | startHomeOnTaskDisplayArea(userId, reason, taskDisplayArea,
                                allowInstrumenting, fromHomeKey),
                false /* initValue */);
    }
}

3.2.4 RootWindowContainer.startHomeOnTaskDisplayArea()

他的主要工作是

调用AMS的getHomeIntent()获取action=MAIN and category=home的Intent

接着调用本类的resolveHomeActivity(),该方法会通过PMS查询得到homeIntent对应的ActivityInfo和对应的applicationinfo,即得到Launcher3的信息。

调用ActivityStartController.startHomeActivity()

class RootWindowContainer extends WindowContainer<DisplayContent>
        implements DisplayManager.DisplayListener {
    ActivityTaskManagerService mService;

    boolean startHomeOnTaskDisplayArea(int userId, String reason, TaskDisplayArea taskDisplayArea,
            boolean allowInstrumenting, boolean fromHomeKey) {
        // Fallback to top focused display area if the provided one is invalid.
        // AMS.systemReady()启动home activity时taskDisplayArea=null
        if (taskDisplayArea == null) {
            final Task rootTask = getTopDisplayFocusedRootTask();
            taskDisplayArea = rootTask != null ? rootTask.getDisplayArea()
                    : getDefaultTaskDisplayArea();
        }

        Intent homeIntent = null;
        ActivityInfo aInfo = null;
        if (taskDisplayArea == getDefaultTaskDisplayArea()) {
            // 1.调用ATMS的获取Category=home的Intent
            homeIntent = mService.getHomeIntent();
            // 2.解析homeIntent对应的ActivityInfo,包含applicationInfo,即得到Launcher3的信息
            aInfo = resolveHomeActivity(userId, homeIntent);
        } else if (shouldPlaceSecondaryHomeOnDisplayArea(taskDisplayArea)) {
            Pair<ActivityInfo, Intent> info = resolveSecondaryHomeActivity(userId, taskDisplayArea);
            aInfo = info.first;
            homeIntent = info.second;
        }
        if (aInfo == null || homeIntent == null) {
            return false;
        }

        if (!canStartHomeOnDisplayArea(aInfo, taskDisplayArea, allowInstrumenting)) {
            return false;
        }

        // Updates the home component of the intent.
        homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
        homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
        // Updates the extra information of the intent.
        if (fromHomeKey) { //该fromHomeKey=false
            homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
            if (mWindowManager.getRecentsAnimationController() != null) {
                mWindowManager.getRecentsAnimationController().cancelAnimationForHomeStart();
            }
        }
        homeIntent.putExtra(WindowManagerPolicy.EXTRA_START_REASON, reason);

        // 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);
        return true;
    }
}

3.2.5 ATMS.getHomeIntent()

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    ComponentName mTopComponent;
    String mTopAction = Intent.ACTION_MAIN;
    String mTopData;
    //返回的是action=MAIN and category=home的Intent。
    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;
    }
}

3.2.6 RootWindowContainer.resolveHomeActivity()

该方法解析HomeIntent对应的ActivityInfo和application info。

class RootWindowContainer extends WindowContainer<DisplayContent>
        implements DisplayManager.DisplayListener {

    ActivityInfo resolveHomeActivity(int userId, Intent homeIntent) {
        final int flags = ActivityManagerService.STOCK_PM_FLAGS;
        final ComponentName comp = homeIntent.getComponent();
        ActivityInfo aInfo = null;
        try {
            if (comp != null) {
                // Factory test.
                aInfo = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
            } else {
                final String resolvedType =
                        homeIntent.resolveTypeIfNeeded(mService.mContext.getContentResolver());
                //根据homeIntent在PMS中查找得到最优的activity
                final ResolveInfo info = AppGlobals.getPackageManager()
                        .resolveIntent(homeIntent, resolvedType, flags, userId);
                if (info != null) {
                    aInfo = info.activityInfo;
                }
            }
        } catch (RemoteException e) {
            // ignore
        }

        if (aInfo == null) {
            Slog.wtf(TAG, "No home screen found for " + homeIntent, new Throwable());
            return null;
        }

        aInfo = new ActivityInfo(aInfo);
        aInfo.applicationInfo = mService.getAppInfoForUser(aInfo.applicationInfo, userId);
        return aInfo;
    }
}

3.2.7 ActivityStartController.startHomeActivity()

该方法主要是获取ActivityStarter对象,由他负责activity的启动,通过设置各种参数,最后调用其excute()真正启动homeActivity。

public class ActivityStartController {
    private final ActivityTaskSupervisor mSupervisor;
private int mLastHomeActivityStartResult;
    
    ActivityStarter obtainStarter(Intent intent, String reason) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }

    void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason,
            TaskDisplayArea taskDisplayArea) {
        final ActivityOptions options = ActivityOptions.makeBasic();
        options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
        if (!ActivityRecord.isResolverActivity(aInfo.name)) {
            // The resolver activity shouldn't be put in root home task because when the
            // foreground is standard type activity, the resolver activity should be put on the
            // top of current foreground instead of bring root home task to front.
            options.setLaunchActivityType(ACTIVITY_TYPE_HOME);
        }
        final int displayId = taskDisplayArea.getDisplayId();
        options.setLaunchDisplayId(displayId);
        options.setLaunchTaskDisplayArea(taskDisplayArea.mRemoteToken
                .toWindowContainerToken());

        // The home activity will be started later, defer resuming to avoid unnecessary operations
        // (e.g. start home recursively) when creating root home task.
        mSupervisor.beginDeferResume();
        final Task rootHomeTask;
        try {
            // Make sure root home task exists on display area.
            rootHomeTask = taskDisplayArea.getOrCreateRootHomeTask(ON_TOP);
        } finally {
            mSupervisor.endDeferResume();
        }
        //调用obtainStarter获取一个ActivityStarter对象,由它负责Activity的启动
        //设置各种参数,最后执行excute()来启动Home Activity
        mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
                .setOutActivity(tmpOutRecord)
                .setCallingUid(0)
                .setActivityInfo(aInfo)
                .setActivityOptions(options.toBundle())
                .execute();
        mLastHomeActivityStartRecord = tmpOutRecord[0];
        if (rootHomeTask.mInResumeTopActivity) {
            // 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();
        }
    }

3.2.8 ActivityStarter.execute()

class ActivityStarter {
    int execute() {
        ...
        int res;
        res = executeRequest(mRequest); 
        ...
    }
}

3.2.9 ActivityStarter.executeRequset()

class ActivityStarter {
    private ActivityRecord mLastStartActivityRecord;
    int execute() {
        ...
        // 创建ActivityRecord
        final ActivityRecord r = new ActivityRecord.Builder(mService)...build();
        mLastStartActivityRecord = r;
        ...
        //调用startActivityUnchecked()启动activity
        mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
                request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
                restrictedBgActivity, intentGrants);

        if (request.outActivity != null) {
            request.outActivity[0] = mLastStartActivityRecord;
        }
        return mLastStartActivityResult; 
    }
}

3.2.10  ActivityStarter.startActivityUnchecked() 

class ActivityStarter {
    int startActivityUnchecked() {
        int result = START_CANCELED;
        final Task startedActivityRootTask;
        ...
        try {
            mService.deferWindowLayout();
            result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
            ...
        } finally {
            startedActivityRootTask = handleStartResult(r, result); 
            ...
        }
    }
}

3.2.11 ActivityStarter.startActivityInner() 

class ActivityStarter {
    int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, Task inTask,
            boolean restrictedBgActivity, NeededUriGrants intentGrants) {
        ...
        final ActivityRecord targetTaskTop = newTask
                ? null : targetTask.getTopNonFinishingActivity();
        if (targetTaskTop != null) {
            // Recycle the target task for this launch.
            startResult = recycleTask(targetTask, targetTaskTop, reusedTask, intentGrants);
            if (startResult != START_SUCCESS) {
                return startResult;
            }
        } else {
            mAddingToTask = true;
        }
        ...
        mRootWindowContainer.resumeFocusedTasksTopActivities(
                        mTargetRootTask, mStartActivity, mOptions, mTransientLaunch);
        ...  
    }
}

3.2.12 RootWindowContainer.resumeFocusedTasksTopActivities()  

class RootWindowContainer extends WindowContainer<DisplayContent>
        implements DisplayManager.DisplayListener {
    boolean resumeFocusedTasksTopActivities(
            Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions,
            boolean deferPause) {  
        boolean result = false;
        if (targetRootTask != null && (targetRootTask.isTopRootTaskInDisplayArea()
                || getTopDisplayFocusedRootTask() == targetRootTask)) {
            result = targetRootTask.resumeTopActivityUncheckedLocked(target, targetOptions,
                    deferPause);
        }
        ...
    } 
}

 3.2.13 Task.resumeFocusedTasksTopActivities()  

class Task extends WindowContainer<WindowContainer> {
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options,
            boolean deferPause) {
        ...
        boolean someActivityResumed = false;
        try {
            mInResumeTopActivity = true;

            if (isLeafTask()) {
                if (isFocusableAndVisible()) {
                    someActivityResumed = resumeTopActivityInnerLocked(prev, options, deferPause);
                }
            }...
        ...  
    }
}

3.2.14 Task.resumeTopActivityInnerLocked()   

class Task extends WindowContainer<WindowContainer> {
    final ActivityTaskSupervisor mTaskSupervisor;
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options,
            boolean deferPause) {
        ...
        mTaskSupervisor.startSpecificActivity(next, true, true);
        ...  
    }
}

3.2.15 ActivityTaskSupervisor .startSpecificActivity()    

该方法是判断要启动activity的进程是否已存在,存在的话调用自身的realStartActivityLocked(),不存在则最终会调用AMS.startProcessAsync()。

接下来就是AMS向Zygote进程请求fork一个launcher进程,就完成了Launcher应用的启动。

不再深入研究了,看的太累了,之后有时间的话,会总结下AMS启动各个app的过程。

public class ActivityTaskSupervisor implements RecentTasks.Callbacks {
    final ActivityTaskManagerService mService;
    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        //1. 判断Launcher的进程是否运行
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);

        boolean knownToBeDead = false;
        if (wpc != null && wpc.hasThread()) {
            try {
                //1.1 要启动的activity的进程已存在,则启动该activity.
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
            knownToBeDead = true;
        }

        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
        //1.2 Launcher的进程不存在,则调用ATMS来启动进程
        final boolean isTop = andResume && r.isTopRunningActivity();
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }    
}

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android系统在启动过程中,会依次启动各个系统服务,其中也包括Launcher服务。LauncherAndroid系统的桌面显示服务,它负责管理并显示设备的主屏幕和应用程序列表。Launcher服务在Android系统的最后阶段启动,即在主界面启动之前。 当设备完成各个系统服务的启动,并且系统进入正常运行状态时,Launcher服务会被启动。系统启动时,先启动底层服务如Zygote进程、SystemServer进程等,然后再启动Android应用进程。Launcher服务作为最基本的应用程序之一,需要在其他应用程序之前加载,以确保用户可以正常使用设备的主屏幕。 Launcher服务的启动主要通过系统服务管理器来实现。系统服务管理器负责管理Android系统的各项服务,并按照事先定义好的优先级顺序启动服务。在启动Launcher服务时,系统服务管理器会调用相应的启动函数,加载Launcher相关的资源和配置文件,并开始监控用户对桌面的操作。 一旦Launcher服务启动成功,就会显示设备的主屏幕,并加载应用程序列表。通过Launcher服务,用户可以查看和管理设备上已安装的应用程序,并快捷地启动它们。同时,Launcher服务还提供了桌面小部件、壁纸等个性化设置,使用户可以自定义设备的外观和功能。 总而言之,Android系统的Launcher服务在启动过程的最后阶段启动,它管理和显示设备的主屏幕和应用程序列表,为用户提供方便的桌面操作和个性化设置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值