ActivityManagerService启动过程分析详解手机开发

之前讲Android的View的绘制原理和流程的时候,讲到过在Android调用setContentView之后,Android调用了一个prepreTravle的方法,这里面就提到了ActivityManagerService。

ActivityManagerService提供的主要功能:
       (1)统一调度各应用程序的Activity
       (2)内存管理
       (3)进程管理

上一篇我们分析Android启动过程的文章中我们分析到了SystemServer,当时我们只是简单的描述了下,Android启动过程分析,我们还是来看一张启动的流程图,

ActivityManagerService启动过程分析详解手机开发

System Server代码位于://frameworks/base/services/java/com/android/server/SystemServer.java

我们来看一段启动的代码:

private void run() { 
     
    // 准备SystemServer运行环境:设置线程优先级,创建主线层Looper,ActivityThread和SystemContext 
    android.os.Process.setThreadPriority(); 
    Looper.prepareMainLooper(); 
     
    // 创建systemserver上进程的ActivityThread和SystemContext 
    createSystemContext(); 
     
    // 增加SystemServiceManager:统一管理system services的创建,启动和生命周期,多用户切换 
    mSystemServiceManager = new SystemServiceManager(mSystemContext); 
     
    // Start services. 
     
    // 1.创建AMS 
    mActivityManagerService = mSystemServiceManager.startService( 
            ActivityManagerService.Lifecycle.class).getService(); 
     
     
    // Start the Power Manager service 
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); 
 
     
    // Start the package manager service 
    mPackageManagerService = PackageManagerService.main(); 
             
     
    // 2.将SystemServer进程可加到AMS中调度管理 
    mActivityManagerService.setSystemProcess(); 
     
    // 3.将相关provider运行在systemserver进程中:SettingsProvider 
    mActivityManagerService.installSystemProviders(); 
     
    //  
    final Watchdog watchdog = Watchdog.getInstance(); 
    watchdog.init(context, mActivityManagerService); 
     
    // Start Window Manager  
    wm = WindowManagerService.main(); 
     
    // 4.直接保存wms对象,与WMS交互 
    mActivityManagerService.setWindowManager(wm); 
     
    // 5.通过WMS 弹出“正在启动应用”框 
    // R.string.android_upgrading_starting_apps 
    ActivityManagerNative.getDefault().showBootMessage(); 
     
    // 6. AMS作为Framework核心,做好准备就绪后就开始启动应用层,和对AMS有依赖的服务 
    mActivityManagerService.systemReady(new Runnable(){ 
        //启动SystemUI 
        startSystemUi(context); 
         
        //启动WatchDog监控核心服务状态 
        Watchdog.getInstance().start(); 
         
        // 
        mmsServiceF.systemRunning(); 
    }); 
 
    // Loop forever. 
    Looper.loop(); 
}

上面的6个步骤就是SystemServer中关于AMS的调用,完成AMS的创建和系统的初始化,以及与WMS交互等流程。

一、ActivityManagerService 创建过程

mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();

通过SystemServiceManager这样一个模板类来创建运行在SystemServer中的Framework服务。并将创建的服务统一保存在队列管理。

public ActivityManagerService(Context systemContext) { 
         
       // 1.系统Context 和 ActivityThread (将systemserver进程作为应用进程管理) 
        mContext = systemContext; 
        mFactoryTest = FactoryTest.getMode(); 
        mSystemThread = ActivityThread.currentActivityThread(); 
         
        // 2.AMS工作的线程和Handler,处理显示相关的UiHandler  ---》知识点HandlerThread和Handler 
        mHandlerThread = new ServiceThread(TAG, 
            android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 
        mHandlerThread.start(); 
        mHandler = new MainHandler(mHandlerThread.getLooper()); 
        mUiHandler = new UiHandler(); 
         
        // 3. 广播队列BroadcastQueue初始化:前台广播队列和后台广播队列 
        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; 
         
        // 4. Service 和 Provider 管理 
        mServices = new ActiveServices(this); 
        mProviderMap = new ProviderMap(this); 
         
        // 5.系统数据存放目录:/data/system/ 
        File dataDir = Environment.getDataDirectory(); 
        File systemDir = new File(dataDir, "system"); 
        systemDir.mkdirs(); 
         
         
        // 电池状态信息,进程状态 和 应用权限管理 
        mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);     
        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 
        mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler); 
         
        // 6.多用户管理 
        mStartedUsers.put(UserHandle.USER_OWNER, new UserState(UserHandle.OWNER, true)); 
        mUserLru.add(UserHandle.USER_OWNER); 
        updateStartedUserArrayLocked(); 
 
        // 7.最近任务,Activity,Task管理 
        mRecentTasks = new RecentTasks(this); 
        mStackSupervisor = new ActivityStackSupervisor(this, mRecentTasks); 
        mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, mRecentTasks); 
         
        // 创建一个新线程,用于监控和定时更新系统CPU信息,30分钟更新一次CPU和电池信息 
        mProcessCpuTracker.init(); 
        mProcessCpuThread = new Thread("CpuTracker") {} 
         
        // 加入Watchdog监控起来 
        Watchdog.getInstance().addMonitor(this); 
        Watchdog.getInstance().addThread(mHandler); 
    }

二、将SystemServer进程可加到AMS中调度管理

mActivityManagerService.setSystemProcess();
mActivityManagerService将system扔到ams统一管理和调度

public void setSystemProcess() { 
        // 将服务加入到ServiceManager中 
        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)); 
         
        // 设置application info LoadedApkinfo 有关 framework-res.apk 
        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 
                    "android", STOCK_PM_FLAGS); 
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 
         
        //给SystemServer进程创建ProcessRecord,adj值,就是将SystemServer进程加入到AMS进程管理机制中,跟应用进程一致 
        synchronized (this) { 
            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(); 
        } 
    }

这一步就是给SystemServer进程创建ProcessRecord,adj值,就是将SystemServer进程加入到AMS进程管理。

三、创建运行在SystemServer进程中Provider

mActivityManagerService.installSystemProviders();

取出进程名为”system”,user_id为SYSTEM_UID的进程信息 ,生成运行在system进程中的providerInfo,并交给上下文的Provider。这段代码的任务就是查询与安装Content Provider并且发布,其中查询出来的provider为SettingsProvider

public final void installSystemProviders() {   
        List<ProviderInfo> providers;   
        synchronized (this) {   
            //取出进程名为"system",user_id为SYSTEM_UID的进程信息   
            ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID);   
            //生成运行在system进程中的providerInfo,表示一个Content Provider。   
            providers = generateApplicationProvidersLocked(app);   
            if (providers != null) {   
                for (int i=providers.size()-1; i>=0; i--) {   
                    ProviderInfo pi = (ProviderInfo)providers.get(i);   
                    //过滤掉非系统apk   
                    if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {   
                        Slog.w(TAG, "Not installing system proc provider " + pi.name   
                                + ": not system .apk");   
                        providers.remove(i);   
                    }   
                }   
            }   
        }   
        if (providers != null) {   
           //安装provider   
            mSystemThread.installSystemProviders(providers);   
        }   
        //监听Settings数据库变化。   
        mCoreSettingsObserver = new CoreSettingsObserver(this);   
   
        //mUsageStatsService.monitorPackages();

四、
AMS systemReady过程

mActivityManagerService.systemReady();

发送ACTION_PRE_BOOT_COMPLETE方法,清理启动的persistent进程,读取Settings配置,运行runnable接口,启动SystemUI,启动persistent应用程序,启动home,发送ACTION_BOOT_COMPLETE广播

public void systemReady(final Runnable goingCallback) { 
        synchronized(this) { 
            if (mSystemReady) { 
                goingCallback.run(); 
            } 
            …… 
             
            // 1.升级相关处理:发送PRE_BOOT_COMPLETED广播 等待升级处理完成才能继续 
            // Check to see if there are any update receivers to run. 
            if (!mDidUpdate) { 
                // 等待升级完成,否则直接返回 
                if (mWaitingUpdate) { 
                    return; 
                } 
                // 发送PRE_BOOT_COMPLETED广播 
                final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>(); 
                mWaitingUpdate = deliverPreBootCompleted(new Runnable() { 
                    // 等待所有接收PRE_BOOT_COMPLETED广播者处理完毕 
                    public void run() { 
                        synchronized (ActivityManagerService.this) { 
                            mDidUpdate = true; 
                        } 
                        showBootMessage(mContext.getText( 
                                R.string.android_upgrading_complete), 
                                false); 
                                 
                        // 将系统版本号和处理过的广播写入文件:/data/system/called_pre_boots.dat文件 
                        writeLastDonePreBootReceivers(doneReceivers); 
                         
                        // 继续systemReady流程 
                        systemReady(goingCallback); 
                    } 
                }, doneReceivers, UserHandle.USER_OWNER); 
 
                if (mWaitingUpdate) { 
                    return; 
                } 
                mDidUpdate = true; 
            } 
 
            mSystemReady = true; 
        } 
         
        // 2. 收集已经启动的进程并杀死,除过persistent常驻进程 
        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); 
                    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.系统准备好后回调传入的Runnable: 
        if (goingCallback != null) goingCallback.run(); 
         
     
      // 4. 发送账户启动的广播,涉及多用户 
      long ident = Binder.clearCallingIdentity(); 
 
 
      Intent intent = new Intent(Intent.ACTION_USER_STARTED); 
      broadcastIntentLocked(intent); 
      intent = new Intent(Intent.ACTION_USER_STARTING); 
      broadcastIntentLocked(intent); 
 
 
      Binder.restoreCallingIdentity(ident); 
 
        // 5. 启动桌面Home Activity 
        mBooting = true; 
        startHomeActivityLocked(mCurrentUserId, "systemReady"); 
        mStackSupervisor.resumeTopActivitiesLocked(); 
  }

参考:

http://www.cnblogs.com/bastard/p/5770573.html

http://blog.csdn.net/u010083774/article/details/50620355

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/5962.html

(0)
上一篇 2021年7月17日
下一篇 2021年7月17日

相关推荐

发表回复

登录后才能评论