Android8.1 Launcher3启动源码解析之AMS启动过程

本次将讲解Launcher启动过程,将从AMS中启动Launcher开始说起

一、SystemServiceManager启动服务过程

在说AMS启动之前有必要说一下SSM是怎样启动service启动的,这个之前关系后面理解AMS启动过程中一些操作。首先看一个在SM中是怎样启动服务的

  traceBeginAndSlog("StartInstaller");
    Installer installer = mSystemServiceManager.startService(Installer.class); /
    traceEnd();

在这里可以看出是调用SystemServiceManager的startService方法,那么接下来就看一下SystemServiceManager源码

public class SystemServiceManager {
    private static final String TAG = "SystemServiceManager";
    private static final int SERVICE_CALL_WARN_TIME_MS = 50;

    private final Context mContext;
    private boolean mSafeMode;
    private boolean mRuntimeRestarted;

    // Services that should receive lifecycle events.
    private final ArrayList mServices = new ArrayList();

    private int mCurrentPhase = -1;

    SystemServiceManager(Context context) {
        mContext = context;
    }

    /**
     * Starts a service by class name.
     *
     * @return The service instance.
     */
    @SuppressWarnings("unchecked")
    public SystemService startService(String className) {
        final Class serviceClass;
        try {
            serviceClass = (Class)Class.forName(className);//根据类型反射出类
        } catch (ClassNotFoundException ex) {
            Slog.i(TAG, "Starting " + className);
            throw new RuntimeException("Failed to create service " + className
                    + ": service class not found, usually indicates that the caller should "
                    + "have called PackageManager.hasSystemFeature() to check whether the "
                    + "feature is available on this device before trying to start the "
                    + "services that implement it", ex);
        }
        return startService(serviceClass);
    }

    /**
     * Creates and starts a system service. The class must be a subclass of
     * {@link com.android.server.SystemService}.
     *
     * @param serviceClass A Java class that implements the SystemService interface.
     * @return The service instance, never null.
     * @throws RuntimeException if the service fails to start.
     */
    @SuppressWarnings("unchecked")
    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

            // Create the service.
            if (!SystemService.class.isAssignableFrom(serviceClass)) {
                throw new RuntimeException("Failed to create " + name
                        + ": service must extend " + SystemService.class.getName());
            }
            final T service;
            try {
                //反射找到目标类中的构造函数
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);//创建实例
            } catch (InstantiationException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service could not be instantiated", ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (NoSuchMethodException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (InvocationTargetException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service constructor threw an exception", ex);
            }

            startService(service);//创建实例成功滴啊用另外一个方法
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }

    public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart();//调用目标类中onStart方法
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
    }
    ......
}

从上面代码我们可以看到以下几点

  • 首先传递一个目标类的字符串过来,然后反射找到目标类
  • 通过目标类找到类中的构造函数,然后调用构造函数创建实例对象
  • 使用上一步创建的实例对象调用其中的onStart方法

至此SystemServiceManager启动service的过程讲完,下面开始讲AMS的启动过程

二、ActivityManagerService启动

在SystemServer启动的时候会启动各种ManagerService,当然ActivityManagerService也是在这个时候启动。下面从SystemServer已启动过程中看AMS启动:

一、SystemServer启动

/**
 * The main entry point from zygote.
 */
public static void main(String[] args) { //这里就是从Zygote进入SystemServer胡入口
    new SystemServer().run();  //new了一个对象然后执行run方法
}
public SystemServer() {
    // Check for factory test mode.
    mFactoryTestMode = FactoryTest.getMode();
    // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
    mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
}
private void run() {
    try {
        ......
        System.loadLibrary("android_servers");
        // Check whether we failed to shut down last time we tried.
        // This call may not return.
        performPendingShutdown();
        // Initialize the system context.
        createSystemContext(); //创建系统全局上下文变量Context
        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext);//创建用于管理service的系统管理对象
        mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // Prepare the thread pool for init tasks that can be parallelized
        SystemServerInitThreadPool.get();
    } finally {
        traceEnd();  // InitBeforeStartServices
    }
    // Start services.
    try {//这里是启动所有系统所需Service的地方
        traceBeginAndSlog("StartServices");
        startBootstrapServices(); //1-启动引导启动的服务
        startCoreServices();      //2-启动核心服务
        startOtherServices();     //3-启动其他服务
        SystemServerInitThreadPool.shutdown();
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        traceEnd();
    }
  ......
}

这部分代码非常好理解,首先是从zygote启动SystemServer的代码。从静态Main主函数开始,创建了一个对象,然后执行启动各种服务。由于这里我直说AMS,因此与AMS无关的代码就不多做说明,直奔主题。

1、startBootStrapServices()启动引导服务

private void startBootstrapServices() {
    ......
    // Wait for installd to finish starting up so that it has a chance to
    // create critical directories such as /data/user with the appropriate
    // permissions.  We need this to complete before we initialize other services.
    traceBeginAndSlog("StartInstaller");
    Installer installer = mSystemServiceManager.startService(Installer.class); //启动安装APK所需的Installer服务
    traceEnd();
    ......
    traceBeginAndSlog("StartActivityManager");
    //在这里使用的AMS内部类Lifecycle生成AMS的对象并完成服务启动
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager); //设置AMS的系统管理服务
    mActivityManagerService.setInstaller(installer);  //设置AMS的安装APK的服务
    traceEnd();
    // Power manager needs to be started early because other services need it.
    // Native daemons may be watching for it to be registered so it must be ready
    // to handle incoming binder calls immediately (including being able to verify
    // the permissions for those calls).
    traceBeginAndSlog("StartPowerManager");
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    traceEnd();
    // Now that the power manager has been started, let the activity manager
    // initialize power management features.
    traceBeginAndSlog("InitPowerManagement");
    mActivityManagerService.initPowerManagement();//初始化AMS中的电量管理服务
    traceEnd();
   ......
}
从这里可以看出在启动AMS的时候需要使用AMS的内部类来启动,并且需要将APK安装的Installer服务对象传递到AMS中。不难看出,AMS是需要初始化电量管理服务的,毕竟需要将电量显示到界面中。首先看一下AMS中关于内部类初始化AMS的过程

public static final class Lifecycle extends SystemService {
    private final ActivityManagerService mService;

    public Lifecycle(Context context) {
        super(context);
        mService = new ActivityManagerService(context);
    }

    @Override
    public void onStart() {
        mService.start();
    }

    @Override
    public void onCleanupUser(int userId) {
        mService.mBatteryStatsService.onCleanupUser(userId);
    }

    public ActivityManagerService getService() {
        return mService;
    }
}
在文章一开始我们就有讲过SystemServiceManager怎么启动service的过程,这里就不难理解。首先实例化一个对象,然后调用onStart()方法。

public ActivityManagerService(Context systemContext) {
    LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    mInjector = new Injector();
    mContext = systemContext;

    mFactoryTest = FactoryTest.getMode(); //默认情况下是不会启动工程模式
    mSystemThread = ActivityThread.currentActivityThread(); //将当前线程设置为系统线程
    mUiContext = mSystemThread.getSystemUiContext(); //获取线程中上下文

    Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());

    mPermissionReviewRequired = mContext.getResources().getBoolean(
            com.android.internal.R.bool.config_permissionReviewRequired);

    //创建Handler线程
    mHandlerThread = new ServiceThread(TAG,
            THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    //创建MainHandler实例
    mHandler = new MainHandler(mHandlerThread.getLooper());
    mUiHandler = mInjector.getUiHandler(this);

    //创建常量对象实例
    mConstants = new ActivityManagerConstants(this, mHandler);

    /* static; one-time init here */
    if (sKillHandler == null) {
        sKillThread = new ServiceThread(TAG + ":kill",
                THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
        sKillThread.start();
        sKillHandler = new KillHandler(sKillThread.getLooper());
    }

    //创建广播队列
    mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "foreground", BROADCAST_FG_TIMEOUT, false);
    mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "background", BROADCAST_BG_TIMEOUT, true);
    mBroadcastQueues[0] = mFgBroadcastQueue;
    mBroadcastQueues[1] = mBgBroadcastQueue;

    mServices = new ActiveServices(this);
    mProviderMap = new ProviderMap(this);
    mAppErrors = new AppErrors(mUiContext, this);

    // TODO: Move creation of battery stats service outside of activity manager service.
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    systemDir.mkdirs();
    mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
    mBatteryStatsService.getActiveStatistics().readLocked();
    mBatteryStatsService.scheduleWriteToDisk();
    mOnBattery = DEBUG_POWER ? true
            : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
    mBatteryStatsService.getActiveStatistics().setCallback(this);

    mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

    mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
    mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
            new IAppOpsCallback.Stub() {
                @Override public void opChanged(int op, int uid, String packageName) {
                    if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
                        if (mAppOpsService.checkOperation(op, uid, packageName)
                                != AppOpsManager.MODE_ALLOWED) {
                            runInBackgroundDisabled(uid);
                        }
                    }
                }
            });

    mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));

    mUserController = new UserController(this);

    mVrController = new VrController(this);

    GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
            ConfigurationInfo.GL_ES_VERSION_UNDEFINED);

    if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
        mUseFifoUiScheduling = true;
    }

    mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
    mTempConfig.setToDefaults();
    mTempConfig.setLocales(LocaleList.getDefault());
    mConfigurationSeq = mTempConfig.seq = 1;
    mStackSupervisor = createStackSupervisor(); //任务栈监听实例
    mStackSupervisor.onConfigurationChanged(mTempConfig);
    mKeyguardController = mStackSupervisor.mKeyguardController;
    mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
    mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 
    mTaskChangeNotificationController =
            new TaskChangeNotificationController(this, mStackSupervisor, mHandler);//任务修改提醒控制
    mActivityStarter = new ActivityStarter(this, mStackSupervisor); //创建用于启动Activity的启动器
    mRecentTasks = new RecentTasks(this, mStackSupervisor); //当前任务

    mProcessCpuThread = new Thread("CpuTracker") { //监听CPU使用情况
        @Override
        public void run() {
            synchronized (mProcessCpuTracker) {
                mProcessCpuInitLatch.countDown();
                mProcessCpuTracker.init();
            }
            while (true) {
                try {
                    try {
                        synchronized(this) {
                            final long now = SystemClock.uptimeMillis();
                            long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
                            long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
                            //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
                            //        + ", write delay=" + nextWriteDelay);
                            if (nextWriteDelay < nextCpuDelay) {
                                nextCpuDelay = nextWriteDelay;
                            }
                            if (nextCpuDelay > 0) {
                                mProcessCpuMutexFree.set(true);
                                this.wait(nextCpuDelay);
                            }
                        }
                    } catch (InterruptedException e) {
                    }
                    updateCpuStatsNow();
                } catch (Exception e) {
                    Slog.e(TAG, "Unexpected exception collecting process stats", e);
                }
            }
        }
    };

    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);
}

由此可以看出,在初始化AMS的过程中创建了用于启动Activity的所有的实例对象。至此在启动引领系统启动的service的过程结束,下面开启启动核心服务。直接看在启动其他服务的过程中关于AMS的代码

2、startOtherServices()

/**
 * Starts a miscellaneous grab bag of stuff that has yet to be refactored
 * and organized.
 */
private void startOtherServices() {
    final Context context = mSystemContext;
    VibratorService vibrator = null;
    ......
    mActivityManagerService.systemReady(() -> { //调用AMS中systemReady方法
   .....
        traceBeginAndSlog("StartSystemUI");
        try {
            startSystemUi(context, windowManagerF);
        } catch (Throwable e) {
            reportWtf("starting System UI", e);
        }
  .....
    }
}
static final void startSystemUi(Context context, WindowManagerService windowManager) {
    Intent intent = new Intent();
    intent.setComponent(new ComponentName("com.android.systemui",
            "com.android.systemui.SystemUIService"));
    intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
    //Slog.d(TAG, "Starting service: " + intent);
    context.startServiceAsUser(intent, UserHandle.SYSTEM);
    windowManager.onSystemUiStarted();
}

由于这部分代码太长仅截取了关于AMS的一部分代码,在这里可以看出来我们主要调用AMS的systemReady()方法

3、AMS的systemReady()

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    traceLog.traceBegin("PhaseActivityManagerReady");
    synchronized(this) {
        if (mSystemReady) {//第一次进来肯定是没有准备好的
          ......
        }

        mLocalDeviceIdleController
                = LocalServices.getService(DeviceIdleController.LocalService.class);
        mAssistUtils = new AssistUtils(mContext);
        mVrController.onSystemReady();
        // Make sure we have the current profile info, since it is needed for security checks.
        mUserController.onSystemReady();
        mRecentTasks.onSystemReadyLocked();
        mAppOpsService.systemReady();
        mSystemReady = true;
    }

  ......
    retrieveSettings(); //恢复设置
    final int currentUserId;
    synchronized (this) {
        currentUserId = mUserController.getCurrentUserIdLocked(); //获取当前用户
        readGrantedUriPermissionsLocked();
    }

    if (goingCallback != null) goingCallback.run();//运行systemReady方法中在System中声明的
    traceLog.traceBegin("ActivityManagerStartApps");
    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
            Integer.toString(currentUserId), currentUserId);
    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
            Integer.toString(currentUserId), currentUserId);
    mSystemServiceManager.startUser(currentUserId);

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

        // Start up initial activity.
        mBooting = true;
    ......
        //启动Launcher中的第一个Activity
        startHomeActivityLocked(currentUserId, "systemReady");

        try {
            if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
                Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
                        + " data partition or your device will be unstable.");
                mUiHandler.obtainMessage(SHOW_UID_ERROR_UI_MSG).sendToTarget();
            }
        } catch (RemoteException e) {
        }

        if (!Build.isBuildConsistent()) {
            Slog.e(TAG, "Build fingerprint is not consistent, warning user");
            mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_UI_MSG).sendToTarget();
        }

        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, intent,
                    null, null, 0, null, null, null, AppOpsManager.OP_NONE,
                    null, false, false, MY_PID, SYSTEM_UID,
                    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, intent,
                    null, new IIntentReceiver.Stub() {
                        @Override
                        public void performReceive(Intent intent, int resultCode, String data,
                                                   Bundle extras, boolean ordered, boolean sticky, int sendingUser)
                                throws RemoteException {
                        }
                    }, 0, null, null,
                    new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
                    null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
        } catch (Throwable t) {
            Slog.wtf(TAG, "Failed sending first user broadcasts", t);
        } finally {
            Binder.restoreCallingIdentity(ident);
        }
        mStackSupervisor.resumeFocusedStackTopActivityLocked();
        mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
        traceLog.traceEnd(); // ActivityManagerStartApps
        traceLog.traceEnd(); // PhaseActivityManagerReady
    }
}

由此可以看出,在这里调用startHomeActivityLocked启动了系统的Launcher。

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) { //启动launcher需要这个
        intent.addCategory(Intent.CATEGORY_HOME);
    }
    return intent;
}
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();//获取启动Launcher的意图
    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) {//这里app肯定是null的
            intent.setFlags(intent.getFlags() | Intent.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;
            mActivityStarter.startHomeActivityLocked(intent, aInfo, myReason); //开始启动laucher
        }
    } else {
        Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
    }

    return true;
}
到此为止关于AMS启动过程中关于Launcer启动的过程已经讲完后面的文章讲解Launcher的Activity启动过程






你可能感兴趣的:(Android系统,AMS,Launcher启动)