Android的组件管理(Android N)--ActivityManagerService服务

来源:互联网 发布:php java 前景 编辑:程序博客网 时间:2024/06/16 19:56

ActivityManagerService是Android Framework的核心,它管理着Android系统的4大组件:Activity、Service、ContentProvider、BroadcastReceiver。除此之外,ActivityManagerService还管理和调度所有用户进程。

1、AMS初始化

AMS运行在SystemServer进程中,对象的创建是在SystemServer类初始化时完成的,如下:

        // Activity manager runs the show.        mActivityManagerService = mSystemServiceManager.startService(                ActivityManagerService.Lifecycle.class).getService();        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
从代码中可以看到,这里调用mSystemServiceManager的startService()方法,这个方法将根据传入的参数(类的class)来创建类的实例对象,并注册到ServiceManager中。

ActivityManagerService的构造方法如下:

    // Note: This method is invoked on the main thread but may need to attach various    // handlers to other threads.  So take care to be explicit about the looper.    public ActivityManagerService(Context systemContext) {        mContext = systemContext;        mFactoryTest = FactoryTest.getMode();        //获取运行在SystemServer中的ActivityThread对象        mSystemThread = ActivityThread.currentActivityThread();        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());        // 创建用于处理消息的线程和Handler对象        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());        }        // 创建管理广播的数据结构        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);// 创建管理组件Service的对象        mProviderMap = new ProviderMap(this);// 创建管理组件Provider的对象        mAppErrors = new AppErrors(mContext, 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(); // /data/system/        // 创建BatteryStatsService服务,并创建了BatteryStatsImpl对象        mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);        //读取耗电量记录文件batterystats.bin        mBatteryStatsService.getActiveStatistics().readLocked();        mBatteryStatsService.scheduleWriteToDisk(); // 更新数据        mOnBattery = DEBUG_POWER ? true                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();// 是否在充电        mBatteryStatsService.getActiveStatistics().setCallback(this);// 设置回调        // 创建ProcessStats服务        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));        // 创建AppOpsService服务,/data/system/appops.xml存储各个app的权限设置和操作信息        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);                            }                        }                    }                });        // 打开文件 urigrants.xml        mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));        mUserController = new UserController(this);        // 获取OpenglES的版本        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",            ConfigurationInfo.GL_ES_VERSION_UNDEFINED);        mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));        // mConfiguration 类型为Configuration,用于描述资源文件的配置属性,例如,字体、语言等        mConfiguration.setToDefaults();        mConfiguration.setLocales(LocaleList.getDefault());        mConfigurationSeq = mConfiguration.seq = 1;        //用来收集ANR、进程的CPU使用、电池的统计等信息;访问它时,必须获得此对象的锁。        mProcessCpuTracker.init();        //解析/data/system/packages-compat.xml文件,该文件用于存储那些需要考虑屏幕尺寸的APK信息,可以参考AnidroidManifest.xml        //中的compatible-screens相关说明,当APK所运行的设备不满足要求时,AMS会根据设置的参数以采用屏幕兼容的方式运行它。        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);        // 创建Intent防火墙        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);        // 创建activity的管理对象        mStackSupervisor = new ActivityStackSupervisor(this);        mActivityStarter = new ActivityStarter(this, mStackSupervisor);        mRecentTasks = new RecentTasks(this, mStackSupervisor);        // 创建新的进程,用于定时更新系统信息,跟mProcessCpuTracker交互        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的监控中          Watchdog.getInstance().addMonitor(this);        Watchdog.getInstance().addThread(mHandler);        mIsFreqAggrEnabled = mContext.getResources().getBoolean(                   com.android.internal.R.bool.config_enableFreqAggr);        if(mIsFreqAggrEnabled) {           lFreqAggr_TimeOut = mContext.getResources().getInteger(                   com.android.internal.R.integer.freqaggr_timeout_param);           lFreqAggr_Init_ParamVal = mContext.getResources().getIntArray(                   com.android.internal.R.array.freqaggr_init_param_value);           lFreqAggr_ParamVal = mContext.getResources().getIntArray(                   com.android.internal.R.array.freqaggr_param_value);        }        mIsLaunchBoostv2_enabled = mContext.getResources().getBoolean(                   com.android.internal.R.bool.config_enableLaunchBoostv2);        if(mIsLaunchBoostv2_enabled) {           lBoost_v2_TimeOut = mContext.getResources().getInteger(                   com.android.internal.R.integer.lboostv2_timeout_param);           lBoost_v2_ParamVal = mContext.getResources().getIntArray(                   com.android.internal.R.array.lboostv2_param_value);        }    }

AMS构造方法的只要作用是创建出了4大组件Activity、Service、Broadcast和ContentProvider的管理对象及一些内部对象。

2、理解setSystemProcess()方法

SystemServer中创建了AMS对象后,会调用它的setSystemProcess()方法,如下:

    public void setSystemProcess() {        try {            // 将ActivityManagerService加入到ServiceManager            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);            // ProcessStats是dump进程信息的服务            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);            // MemBinder是dump系统中每个进程的内存使用状况的服务            ServiceManager.addService("meminfo", new MemBinder(this));            //GraphicsBinder是dump系统中每个进程使用图形加速卡状态的服务            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));            //DbBinder是dump系统中每个进程的db状况的服务            ServiceManager.addService("dbinfo", new DbBinder(this));            if (MONITOR_CPU_USAGE) {                ServiceManager.addService("cpuinfo", new CpuBinder(this));            }            // PermissionController是检查Binder调用权限的服务            ServiceManager.addService("permission", new PermissionController(this));            ServiceManager.addService("processinfo", new ProcessInfoService(this));            //得到framework-res.apk的ApplicationInfo            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());            synchronized (this) {//把systemServer本身加入到process的管理中                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);        }    }

setSystemProcess()方法主要是向ServiceManager注册了一些服务。注意最后一段代码,它创建了代表SystemServer的ProcessRecord对象,并把它加入到AMS的进程管理体系中。

上面代码中用到了mPidsSelfLocked变量,我们看下这个变量的定义,
    /**     * All of the processes we currently have running organized by pid.     * The keys are the pid running the application.     *     * <p>NOTE: This object is protected by its own lock, NOT the global     * activity manager lock!     */    final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
mPidsSelfLocked保存有pid组织起来的正在运行的进程,保存的是pid,及pid对应的ProcessRecord。

3、systemReady()方法

SystemServer在启动完所有服务之后,将调用AMS的systemReady()方法。这个方法是Android进入用户交互阶段前最后进行的准备工作。

    public void systemReady(final Runnable goingCallback) {        synchronized(this) {            if (mSystemReady) {//调用时的值为false,不会执行下面的语句                // If we're done calling all the receivers, run the next "boot phase" passed in                // by the SystemServer在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();//调用UserController的updateCurrentProfileIdsLocked()方法。            mRecentTasks.onSystemReadyLocked();//重建带有persistent标记的task            mAppOpsService.systemReady();//AppOps准备工作            mSystemReady = true;//设置mSystemReady变量        }......

(1)、装载系统中用户的profile ID

UserController的onSystemReady()中调用updateCurrentProfileIdsLocked()方法。

    void onSystemReady() {        updateCurrentProfileIdsLocked();    }

Android的许多系统调用都需要检查用户的ID,所以这里调用updateCurrnetProfileIdsLocked()方法来通过UserManagerService读取系统保持的Profile信息,装载系统中已经存在的用户信息。

(2)、重建带有persistent标记的Task

调用RecentTask的onSystemReadyLocked()方法,如下:
    void onSystemReadyLocked() {        clear();        mTaskPersister.startPersisting();    }
从Android5.0开始支持带有persistent标记的task,这些task在关机时,信息保存在/data/system/recent_tasks目录下的xxx_task.xml(xxx表示task id)中,系统重启时,通过这些文件中保存的信息重建task。

(3)、清理进程

        ArrayList<ProcessRecord> procsToKill = null;        synchronized(mPidsSelfLocked) {            for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {                ProcessRecord proc = mPidsSelfLocked.valueAt(i);                if (!isAllowedWhileBooting(proc.info)){//检查进程是否有persistent标记                    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;        }
这段代码的最用是找到已经启动的应用进程,然后杀掉它们。目的是在启动Home前准备一个干净的环境。但是有一种进程是不用退出的,isAllowedWhileBooting()方法会判断进程是否带有FLAG_PERSISTENT标记,如果有就不用退出;因为带有这个标记的进程后面还要启动他们,这里就留下不用清理了。

(4)、如果处于“工厂测试模式”,启动用于工厂测试的模块

        synchronized(this) {            // Make sure we have no pre-ready processes sitting around.            if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {                // 处于工厂模式,则查找测试程序                ResolveInfo ri = mContext.getPackageManager()                        .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),                                STOCK_PM_FLAGS);                CharSequence errorMsg = null;                if (ri != null) {                    ActivityInfo ai = ri.activityInfo;                    ApplicationInfo app = ai.applicationInfo;                    //判断找到的测试程序是否是系统程序                    if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {                        //把测试程序的信息设置在下面的变量中,将会启动测试程序                        mTopAction = Intent.ACTION_FACTORY_TEST;                        mTopData = null;                        mTopComponent = new ComponentName(app.packageName,                                ai.name);                    } else {                        errorMsg = mContext.getResources().getText(                                com.android.internal.R.string.factorytest_not_system);                    }                } else {                    errorMsg = mContext.getResources().getText(                            com.android.internal.R.string.factorytest_no_action);                }                if (errorMsg != null) {//发送出错的信息                    mTopAction = null;                    mTopData = null;                    mTopComponent = null;                    Message msg = Message.obtain();                    msg.what = SHOW_FACTORY_ERROR_UI_MSG;                    msg.getData().putCharSequence("msg", errorMsg);                    mUiHandler.sendMessage(msg);                }            }        }
手机生产时,需要进入工厂模式来执行检测程序,工厂模式下运行的程序需要响应Intent.ACTION_FACTORY_TEST,因此,这里会判断手机是否处于工厂模式,如果是则查找响应改Intent的程序,并放置在mTopComponent变量中,这样将会启动测试程序;如果找不到程序,则发送出错的Message。

(5)、读取设置信息

        retrieveSettings();
调用retrieveSettings()方法来读取设置,这个方法中读取了几种设置。
DEBUG_APP:需要调试的app的名称。
WAIT_FOR_DEBUGGER:值为1表示启动调试的app时要先等待调试器,否则正常启动。
ALWAYS_FINISH_ACTIVITIES:值为1表示Activity不再需要时,系统会立即清除他们。
DEVELOPMENT_FORCE_RTL:值为1表示要将系统设置为从右到左的模式。
LENIENT_BACKGROUND_CHECK。
DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES。
之后再从资源文件中读取几个缺省的系统配置信息。

(6)、执行参数的callback

if (goingCallback != null) goingCallback.run();
这个回调方法是在systemServer中定义的。

(7)、启动当前用户

final int currentUserId;......currentUserId = mUserController.getCurrentUserIdLocked();......mSystemServiceManager.startUser(currentUserId);

(8)、启动带有标记为FLAG_PERSISTENT的应用和Home应用

        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;//启动结束的标记            // Enable home activity for system user, so that the system can always boot            if (UserManager.isSplitSystemUser()) {                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();                }            }            startHomeActivityLocked(currentUserId, "systemReady");//启动Home应用            // start the power off alarm by boot mode            boolean isAlarmBoot = SystemProperties.getBoolean("ro.alarm_boot", false);            if (isAlarmBoot) {                sendAlarmBroadcast();            }            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);//发送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);//发送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);            } catch (Throwable t) {                Slog.wtf(TAG, "Failed sending first user broadcasts", t);            } finally {                Binder.restoreCallingIdentity(ident);            }            mStackSupervisor.resumeFocusedStackTopActivityLocked();            mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
    private void startPersistentApps(int matchFlags) {        if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;        synchronized (this) {            try {//查找系统中带有FLAG_PERSISTENT标记的应用                final List<ApplicationInfo> apps = AppGlobals.getPackageManager()                        .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();                for (ApplicationInfo app : apps) {                    if (!"android".equals(app.packageName)) {//排除掉包名为“android”的应用,前面已经加过了                        addAppLocked(app, false, null /* ABI override */);//启动应用                    }                }            } catch (RemoteException ex) {            }        }    }
这段代码主要是通过调用addAppLocked()方法启动带有FLAG_PERSISTENT标记的应用,通过startHomeActivityLocked()方法启动Home应用,Home启动后,Android将发出Intent.ACTION_BOOT_COMPLETED广播,标志系统启动完成。
SystemReady()方法到此就分析完了。
从上面的分析中可以看出,如果系统应用希望在Home启动前启动,可以加入"FLAG_PERSISTENT"的标志;接收Intent“ACTION_BOOT_COMPLETED”的应用只能在Home启动后再启动。

下面接着分析Android的Process管理部分。

0 0