ActivityManagerService启动分析

AMS系列:
1、Activity生命周期、启动模式和隐式启动总结
2、本文ActivityManagerService启动分析
3、ActivityMnagerService分析之启动一个Acitvity流程分析

本文分析代码基于Android N,ActivityManagerService简称AMS,其它类似;
“…”代表省略部分代码

整体思路

1、android启动linux内核,加载虚拟机,走到framework启动Systemserver;
2、Systemserver启动Activity Manager,Package Manager,Window Manager等等一系列系统服务;
3、分析AMS的启动;
4、本文主要分析AMS初始化干了些什么,其他细节后续再分析;

简述Android启动

简单说一下Android的启动过程:
Android基于Linux,前面和Linux大致相同
按下电源 -> BIOS自检 -> 引导程序 -> 启动kernel -> 启动Init进程(system\core\init\init.c) -> 开启虚拟机(Zygotes)
然后
Zygote会startSystemServer,而Systemserver就开始启动framework层的各种公共服务,AMS、WMS、PMS等…

Systemserver启动AMS

从Systemserver.run开始,这里开始启动各种服务

private void run() {
    ....
    // 初始化system Context
    createSystemContext();

    // 创建system manager
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    ...
    // Start services.
    try {
        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
        // 开始引导Services,Installer创建user/data等目录,
        // 以及MessageMonitorService,AMS,PowerManagerService,LightsService,DisplayManagerService,UserManagerService等
        startBootstrapServices();
        // 核心Services,BatteryService,UsageStatsService,WebViewUpdateService
        startCoreServices();
        // 其他Services,这里启动的服务最多,TelecomLoaderService,CameraService,AccountManagerService等等一系列Service
        startOtherServices();
    } 
    ...
    // Loop forever.
    Looper.loop();
    ...
}

其他服务的启动这里就不展开了,这里开始看AMS的启动

private void startBootstrapServices() {
    ...
    // 创建AMS
    mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
    // 设置对象关联
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
    ...
        // 初始化power manager
    mActivityManagerService.initPowerManagement();
    ...
    // 为系统进程设置应用程序实例
        mActivityManagerService.setSystemProcess();
}
private void startOtherServices() {
    ...
    // 和SettingsProvider关联
    mActivityManagerService.installSystemProviders();
    ...
    // 设置对象关联
    mActivityManagerService.setWindowManager(wm);
    ...
    // 当AMS准备好后,再启动。类似location的服务很多,在ready之前已经创建服务并添加到ServiceManager中
    mActivityManagerService.systemReady(new Runnable() {
        ...
        startSystemUi(context);
        ...
        Watchdog.getInstance().start();
        ...
        if (locationF != null) locationF.systemRunning();
        ...
        ...
    }
}

1.创建ActivityManagerService

mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
实际就是返回一个new ActivityManagerService(context);

    public ActivityManagerService(Context systemContext) {
    // Context 和 ActvityThread
        mContext = systemContext;
        mFactoryTest = FactoryTest.getMode();
        mSystemThread = ActivityThread.currentActivityThread();

    // AMS运行的线程和Handler,还有显示相关的UiHandler
        mHandlerThread = new ServiceThread(TAG,
                android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());
        mUiHandler = new UiHandler();

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

    // Broadcast管理的相关初始化
        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;

    // Server管理的相关初始化
        mServices = new ActiveServices(this);
    // Provider管理的相关初始化
        mProviderMap = new ProviderMap(this);
    // App错误控制
        mAppErrors = new AppErrors(mContext, this);

        // 创建system文件路径
        File dataDir = Environment.getDataDirectory();
        File systemDir = new File(dataDir, "system");
        systemDir.mkdirs();
    // 初始化BatteryStatsService
        mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
        mBatteryStatsService.getActiveStatistics().readLocked();
        mBatteryStatsService.scheduleWriteToDisk();
        mOnBattery = DEBUG_POWER ? true
                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
        mBatteryStatsService.getActiveStatistics().setCallback(this);

    // ProcessStatsService进程来统计不用的app以及不好行为的app的信息
        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

    // 权限管理,安全机制
        mAppOpsService = new AppOpsService(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);

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

        mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));

        mConfiguration.setToDefaults();
        mConfiguration.setLocales(LocaleList.getDefault());

        mConfigurationSeq = mConfiguration.seq = 1;
        mProcessCpuTracker.init();

    // 当APK所运行的设备不满足要求时,AMS会根据设置的参数以采用屏幕兼容的方式去运行它
        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
    // 一些校验
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
    // Activity管理的相关初始化
        mStackSupervisor = new ActivityStackSupervisor(this);
        mActivityStarter = new ActivityStarter(this, mStackSupervisor);
    // 最近任务
        mRecentTasks = new RecentTasks(this, mStackSupervisor);

    // 每半小时跟新CPU信息
        mProcessCpuThread = new Thread("CpuTracker") {
            @Override
            public void run() {
                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);

        /// M: AMEventHook event @{
        AMEventHookData.EndOfAMSCtor eventData =
            AMEventHookData.EndOfAMSCtor.createInstance();
        mAMEventHook.hook(AMEventHook.Event.AM_EndOfAMSCtor,
            eventData);
        /// M: AMEventHook event @}
    }

setSystemProcess

mActivityManagerService.setSystemProcess();
初始化一些服务,为系统进程设置应用程序实例,AMS得到systemserver的ProcessRecord,以便AMS管理systemserver.

    public void setSystemProcess() {
        try {
        // 添加各种服务
            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
            ServiceManager.addService("meminfo", new MemBinder(this));
            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
            ServiceManager.addService("dbinfo", new DbBinder(this));
            if (MONITOR_CPU_USAGE) {
                ServiceManager.addService("cpuinfo", new CpuBinder(this));
            }
            ServiceManager.addService("permission", new PermissionController(this));
            ServiceManager.addService("processinfo", new ProcessInfoService(this));

            /// M: ANRManager mechanism @{
            ServiceManager.addService("anrmanager", mANRManager, true);
            /// @}
    
        // 这里是获得报名为“android”的apk信息,即获得framework-res.apk
            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        // 系统进程加载framework-res.apk
            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
        
        // AMS得到systemserver的ProcessRecord,以便AMS管理systemserver
            synchronized (this) {
        // 从info里得到systemserver所在的系统进程的名字,然后封装成一个ProcessRecord,即封装系统进程的信息
                ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
                app.persistent = true;
                app.pid = MY_PID;
                app.maxAdj = ProcessList.SYSTEM_ADJ;
                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
                synchronized (mPidsSelfLocked) {
                    mPidsSelfLocked.put(app.pid, app);
                }
                updateLruProcessLocked(app, false, null);
                updateOomAdjLocked();
            }
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(
                    "Unable to find android system package", e);
        }
    }

这里说下,ProcessRecord描述一个app所在进程的所有信息。因为AMS是运行在systemserver进程中的,所以这里得到的实际就是systemserver

installSystemProviders

关联管理SettingsProvider
mActivityManagerService.installSystemProviders();

    public final void installSystemProviders() {
        List<ProviderInfo> providers;
        synchronized (this) {
        // 得到名字为“system”,pid为Process.SYSTEM_UID的进程,即systemserver所在系统进程
            ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID);
        // 得到运行在系统进程中的所有ContentProvider的ProviderInfo信息
            providers = generateApplicationProvidersLocked(app);
            if (providers != null) {
                for (int i=providers.size()-1; i>=0; i--) {
                    ProviderInfo pi = (ProviderInfo)providers.get(i);
                    if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
                        Slog.w(TAG, "Not installing system proc provider " + pi.name
                                + ": not system .apk");
            // 过滤掉非系统进程运行的provider
                        providers.remove(i);
                    }
                }
            }
        }
    // 上面已经过滤掉,剩下一个ContentProvider其实就是SettingsProvider
        if (providers != null) {
        // 安装SettingsProvider
            mSystemThread.installSystemProviders(providers);
        }

    // 创建CoreSettingsObserver监听SettingsProvider变化
        mCoreSettingsObserver = new CoreSettingsObserver(this);
        mFontScaleSettingObserver = new FontScaleSettingObserver();

        //mUsageStatsService.monitorPackages();
    }

systemReady

mActivityManagerService.systemReady(new Runnable(){}

先看public void systemReady(final Runnable goingCallback) {}

1、校验进行systemReady

synchronized(this) {
            if (mSystemReady) {
                // If we're done calling all the receivers, run the next "boot phase" passed in
                // by the SystemServer
                if (goingCallback != null) {
                    goingCallback.run();
                }
                return;
            }

            mLocalDeviceIdleController
                    = LocalServices.getService(DeviceIdleController.LocalService.class);

            // Make sure we have the current profile info, since it is needed for security checks.
            mUserController.onSystemReady();
            mRecentTasks.onSystemReadyLocked();
            mAppOpsService.systemReady();
            mSystemReady = true;
        }

2.杀死之前系统进程启动的进程,除过persistent常驻进程

  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);
                    removeProcessLocked(proc, true, false, "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;
        }

3.启动传入的Runable

if (goingCallback != null) goingCallback.run();

4.启动launcher,即HomeActivity

startHomeActivityLocked(currentUserId, "systemReady");

5.发送启动广播

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, Process.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, Process.SYSTEM_UID, UserHandle.USER_ALL);
    } 

再看一下Runnable中做了什么

1、启动carash监听

try {
    mActivityManagerService.startObservingNativeCrashes();
} 

2、WebView设置

if (!mOnlyCore) {
    Slog.i(TAG, "WebViewFactory preparation");
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WebViewFactoryPreparation");
    mWebViewUpdateService.prepareWebViewInSystemServer();
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}

3、启动systemUI

try {
    startSystemUi(context);
} 

4、在systemReady后,各种类开始设置自己的参数

if (networkScoreF != null) networkScoreF.systemReady();
if (networkManagementF != null) networkManagementF.systemReady();
if (networkStatsF != null) networkStatsF.systemReady();
if (locationF != null) locationF.systemRunning();
...//等等,很多类似方法

总结

AMS启动简要概括:
1、new AMS 准备Handler、初始化四大组件相关、权限、多用户、看门狗
2、setSystemProcess 加载framework-res.apk,和systemserver进程建立关系
3、installSystemProviders 配置ContentProvider即SettingsProvider
4、systemReady 最后工作,启动launcher,systemUI,发送启动广播,其他各类组件准备好

Read the fucking sources code!

    原文作者:Yink_Liu
    原文地址: https://www.jianshu.com/p/29e9e1dfa6c2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞