ActivityManagerService简要分析

1、相关类简述

1.1、com.android.server.SystemServer

本身由zygote进程运行,用来启动各种各样的系统服务(SystemService)

1.2、com.android.server.SystemService

运行在系统进程中的service,每个SystemService都是有生命周期的,所有的生命周期函数都是运行在SystemServer的主线程当中。
1.2.1 每个SystemService都有一个参数为Context的构造函数,用来初始化SystemService;
1.2.2 调用onstart()使得SystemService处于运行状态,在这种状态下,该SystemService可以通过publishBinderService(String, IBinder) 方法来向外提供服务(binder interface),
1.2.3 在启动阶段onBootPhase(int)会被不停的调用直到运行到PHASE_BOOT_COMPLETED阶段(启动阶段的最后阶段),在启动的每一阶段都可以完成一些特殊的任务。

1.3、 com.android.server.SystemServiceManager

负责管理SystemService的创建、启动以及其他生命周期函数

1.4、android.app.ActivityManager

用来和系统中所有运行的Activity进行交互,运行在用户进程中;
IActivityManager是一个系统服务,对于上层应用,IActivityManager不希望把所有的接口都暴露出来,因而使用ActivityManager作为中介来访问IActivityManager提供的功能。ActivityManager是通过ActivityManagerNative.getDefault()来获取到IActivityManager这个接口的。因为ActivityManager是运行在用户进程的,因而getDefault()获取的是ActivityManagerProxy.

2、com.android.server.am.ActivityManagerService

2.1 简单类图

《ActivityManagerService简要分析》 QQ截图20160706104100.png

对于使用过AIDL并且看过.aidl文件自动生成的java类的人来说,这个不要太熟悉了,IActivityManager对应自定义的接口,ActivityManagerNative对应Stub,ActivityManagerProxy对应Stub中的proxy,ActivityManagerService对应的就是真正的接口实现者。
可以看到ActivityManagerService并不是一个SystemService,真正的SystemService是它里面的内部类Lifecycle,而Lifecycle持有ActivityManagerService的实例并且其生命周期都是由ActivityManagerService来替代完成的。这样设计,一来使得ActivityManagerService具有SystemService具有的一切特征,二来可以向调用者比如ActivityManager提供特定的功能。

2.2 ActivityManagerService初始化过程

// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;

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

        @Override
        public void onStart() {// 启动该SystemService
            mService.start();
        }

        public ActivityManagerService getService() {
            return mService;
        }
    }

这里的Lifecycle是一个SystemService,内部持有一个ActivityManagerService实例。

2.3 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;//系统进程中的Context
        mFactoryTest = FactoryTest.getMode();
        // 系统进程(framework-res.apk)对应的ActivityThread
        mSystemThread = ActivityThread.currentActivityThread();

        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
        // 创建了一个ServiceThread(HandlerThread)
        mHandlerThread = new ServiceThread(TAG,
                android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        // 创建一个Handler,使用的是ServiceThread的Looper
        mHandler = new MainHandler(mHandlerThread.getLooper());
        // 创建了一个UiHandler,它的Looper是mainLooper
        mUiHandler = new UiHandler();

        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);

        // 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(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 = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);

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

        // User 0 is the first and only user that runs at boot.
        mStartedUsers.put(UserHandle.USER_OWNER, new UserState(UserHandle.OWNER, true));
        mUserLru.add(UserHandle.USER_OWNER);
        updateStartedUserArrayLocked();

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

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

        mConfiguration.setToDefaults();
        mConfiguration.setLocale(Locale.getDefault());

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

        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
        // 最近任务列表
        mRecentTasks = new RecentTasks(this);
        //
        mStackSupervisor = new ActivityStackSupervisor(this, mRecentTasks);
        //
        mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, mRecentTasks);

        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);
    }

2.4 ActivityManagerservice.setSystemProcess()

// Set up the Application instance for the system process and get started.
        // 初始化系统进程的Application并启动它
        mActivityManagerService.setSystemProcess();
 public void setSystemProcess() {
        try {
            // 向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));
            if (MONITOR_CPU_USAGE) {
                ServiceManager.addService("cpuinfo", new CpuBinder(this));
            }
            ServiceManager.addService("permission", new PermissionController(this));
            ServiceManager.addService("processinfo", new ProcessInfoService(this));

            // AndroidManifes.xml中<application>标签解析出来的配置信息保存在这个对象中
                        // 从PackageManagerService中获取framework-res.apk安装包的ApplicationInfo信息
            // 注意这里的使用方式,PackageManagerService和ActivityManagerService运行在同一个进程
            // 这里为什么要使用跨进程的方式来进行通信呢?
            // 原因是保持android环境中和服务交互的一致性,利于以后扩展和维护
            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                    "android", STOCK_PM_FLAGS);
            // 
            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

            synchronized (this) {
                // 生成保存系统进程信息的对象
                ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
                // 保持该进程一直处于运行状态
                app.persistent = true;
                app.pid = MY_PID;
                app.maxAdj = ProcessList.SYSTEM_ADJ;
                // 给该进程对象设置该进程中AMS和其他进程交互的接口
                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);
        }
    }
2.4.1 ActivityThread.installSystemApplicationInfo()
public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
        synchronized (this) {
            // ContextImpl.installSystemApplicationInfo()
            // info:framework-res.apk androidmanifest.xml application标签相关信息
            getSystemContext().installSystemApplicationInfo(info, classLoader);

            // give ourselves a default profiler
            mProfiler = new Profiler();
        }
    }

ContextImpl.installSystemApplicationInfo()

void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
        mPackageInfo.installSystemApplicationInfo(info, classLoader);
    }

LoadedAPK.installSystemApplicationInfo()

/**
     * Sets application info about the system package.
     */
    void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
        assert info.packageName.equals("android");
        mApplicationInfo = info;
        mClassLoader = classLoader;
    }

ActivityManagerservice.setSystemProcess()做的第一件事情是:从PackageManagerService中找到packageName为”android”(framework-res.apk)对应的ApplicationInfo信息,然后填充到apk对应的LoadedApk对象中。从PackageManagerService分析中了解到在系统启动的时候会扫描并解析APK把信息保存到它自己的Map中,所以这里直接从这个map中直接取出来,然后从android系统Context初始化过程中知道,对于packagename为”android”的framework-res.apk,其ApplicationInfo在LoadedApk构造函数中是直接new出来的,是一个空的对象,因而这里从PackageManagerService取出来填充到这里。

2.4.2 ActivityManagerservice.newProcessRecordLocked():创建一个ProcessRecord对象,用来保存系统进程信息
final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess,
            boolean isolated, int isolatedUid) {
            // 进程名
        String proc = customProcess != null ? customProcess : info.processName;
            // 耗电量统计
        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
        final int userId = UserHandle.getUserId(info.uid);
        int uid = info.uid;
        if (isolated) {// 对系统进程该值为false
            if (isolatedUid == 0) {
                int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
                while (true) {
                    if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
                            || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
                        mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
                    }
                    uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
                    mNextIsolatedProcessUid++;
                    if (mIsolatedProcesses.indexOfKey(uid) < 0) {
                        // No process for this uid, use it.
                        break;
                    }
                    stepsLeft--;
                    if (stepsLeft <= 0) {
                        return null;
                    }
                }
            } else {
                // Special case for startIsolatedProcess (internal only), where
                // the uid of the isolated process is specified by the caller.
                uid = isolatedUid;
            }
        }
        // 创建ProcessRecord,用于存储系统进程所在进程的所有信息
        final ProcessRecord r = new ProcessRecord(stats, info, proc, uid);
        if (!mBooted && !mBooting
                && userId == UserHandle.USER_OWNER
                && (info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
            r.persistent = true;
        }
// 添加ProcessRecord 到Map中保存起来
        addProcessNameLocked(r);
        return r;
    }
2.4.3 ApplicationThread简要介绍

首先看类图:

《ActivityManagerService简要分析》 QQ截图20160812181904.png

ApplicationThread具备IApplicationThread所有的能力,是AMS与其他应用交互的桥梁,ActivityThread里面通过mAppThread属性指向它。
<br >
以上,便是ActivityManagerservice.setSystemProcess()的主要工作:一是从PackageManagerService中找到系统APK(framework-res.apk)对应的ApplicationInfo信息,填充到和它对应的LoadedApk对象中;二是创建一个记录其进程信息的对象ProcessRecord并关联IApplicationThread,使得该进程中的AMS能够和其他进程进行交互。

2.5 ActivityManagerService.installSystemProviders();

public final void installSystemProviders() {
        List<ProviderInfo> providers;
        synchronized (this) {
            // 获取进程名为"system",进程    UID为1000的进程
            // 在PMS的Settings中可以知道该进程共享名为"android.uid.system"
            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");
                        providers.remove(i);
                    }
                }
            }
        }
        if (providers != null) {
            // ActivityThread对ContentProvider进行安装
            mSystemThread.installSystemProviders(providers);
        }

        mCoreSettingsObserver = new CoreSettingsObserver(this);

        //mUsageStatsService.monitorPackages();
    }

framework-res.apk中AndroidManifest.xml文件相关配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android" coreApp="true" android:sharedUserId="android.uid.system"
    android:sharedUserLabel="@string/android_system_label">
        <application android:process="system"
                 android:persistent="true"
                 android:hasCode="false"
                 android:label="@string/android_system_label"
                 android:allowClearUserData="false"
                 android:backupAgent="com.android.server.backup.SystemBackupAgent"
                 android:killAfterRestore="false"
                 android:icon="@drawable/ic_launcher_android"
                 android:supportsRtl="true">
        <activity android:name="com.android.internal.app.ChooserActivity"
                android:theme="@style/Theme.DeviceDefault.Resolver"
                android:finishOnCloseSystemDialogs="true"
                android:excludeFromRecents="true"
                android:documentLaunchMode="never"
                android:relinquishTaskIdentity="true"
                android:process=":ui">
            <intent-filter>
                <action android:name="android.intent.action.CHOOSER" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.VOICE" />
            </intent-filter>
        </activity>
        //..........
        <receiver android:name="com.android.server.MasterClearReceiver"
            android:permission="android.permission.MASTER_CLEAR">
            <intent-filter
                    android:priority="100" >
                <!-- For Checkin, Settings, etc.: action=MASTER_CLEAR -->
                <action android:name="android.intent.action.MASTER_CLEAR" />

                <!-- MCS always uses REMOTE_INTENT: category=MASTER_CLEAR -->
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="android.intent.category.MASTER_CLEAR" />
            </intent-filter>
        </receiver>
        <service android:name="com.android.internal.backup.LocalTransportService"
                android:permission="android.permission.CONFIRM_FULL_BACKUP"
                android:exported="false">
            <intent-filter>
                <action android:name="android.backup.TRANSPORT_HOST" />
            </intent-filter>
        </service>
        //.........
    </application>
</manifest>

SettingProvider.apk 中AndroidManifest.xml内容

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.android.providers.settings"
        coreApp="true"
        android:sharedUserId="android.uid.system">

    <application android:allowClearUserData="false"
                 android:label="@string/app_label"
                 android:process="system"
                 android:backupAgent="SettingsBackupAgent"
                 android:killAfterRestore="false"
                 android:icon="@mipmap/ic_launcher_settings">
                 
    <!-- todo add: android:neverEncrypt="true" -->

        <provider android:name="SettingsProvider" android:authorities="settings"
                  android:multiprocess="false"
                  android:exported="true"
                  android:singleUser="true"
                  android:initOrder="100" />
    </application>
</manifest>

从xml文件中可以发现,frameworkwork-res.apk和SettingProvider都运行在名为system的进程中,在2.4中那个创建出来的ProcessRecord以及这里要找的ProcessRecord都是指向这个进程,从清单文件中可以看到,framework-res.apk中是没有provider的,只有settingprovider中有一个,所以这里找到的就是settingprovider中的contentprovider对应的信息ProviderInfo。
在查询到了该进程contentprovider对应的信息后,通过ActivityThread的installSystemProviders()来对其进行安装。查询的详细过程和安装的过程这里略过,这个暂时不是我的重点~~

2.6 ActivityManagerService.systemReady(Runnable callback)

这个方法主要作用是:
1)发送Intent.ACTION_PRE_BOOT_COMPLETED广播,该广播只会被处理一次,接受者接收该广播主要是对数据库做一些处理;
2)清理在启动过程中启动的非persistent进程,persistent进程是需要一直保持运行的进程;
3)读取设置信息:需要调试的程序包名,等待调试的应用,字体大小相关等等
4)加载资源信息
5)运行回调:允许观察native crash了,启动SystemUI.apk等等其他服务;
6)启动persistent应用,启动Launcher.

2.7 Launcher启动过程

ActivityManagerService.startHomeActivityLocked()

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;
        }
        // 取得Launcher对应的Intent
        Intent intent = getHomeIntent();
        // 从PackageManagerService中取得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);
            // Launcher运行进程信息
            ProcessRecord app = getProcessRecordLocked(aInfo.processName,
                    aInfo.applicationInfo.uid, true);
            // 如果Launcher没有启动,则启动它
            if (app == null || app.instrumentationClass == null) {
                //
                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
                //mStackSupervisor初始化在构造函数中,启动Launcher
                mStackSupervisor.startHomeActivity(intent, aInfo, reason);
            }
        }

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