ActivityManagerService简要分析
1、相關(guān)類簡述
1.1、com.android.server.SystemServer
本身由zygote進(jìn)程運(yùn)行,用來啟動(dòng)各種各樣的系統(tǒng)服務(wù)(SystemService)
1.2、com.android.server.SystemService
運(yùn)行在系統(tǒng)進(jìn)程中的service,每個(gè)SystemService都是有生命周期的,所有的生命周期函數(shù)都是運(yùn)行在SystemServer的主線程當(dāng)中。
1.2.1?每個(gè)SystemService都有一個(gè)參數(shù)為Context的構(gòu)造函數(shù),用來初始化SystemService;
1.2.2?調(diào)用onstart()使得SystemService處于運(yùn)行狀態(tài),在這種狀態(tài)下,該SystemService可以通過publishBinderService(String, IBinder)?方法來向外提供服務(wù)(binder interface),
1.2.3?在啟動(dòng)階段onBootPhase(int)會(huì)被不停的調(diào)用直到運(yùn)行到PHASE_BOOT_COMPLETED階段(啟動(dòng)階段的最后階段),在啟動(dòng)的每一階段都可以完成一些特殊的任務(wù)。
1.3、 com.android.server.SystemServiceManager
負(fù)責(zé)管理SystemService的創(chuàng)建、啟動(dòng)以及其他生命周期函數(shù)
1.4、android.app.ActivityManager
用來和系統(tǒng)中所有運(yùn)行的Activity進(jìn)行交互,運(yùn)行在用戶進(jìn)程中;
IActivityManager是一個(gè)系統(tǒng)服務(wù),對(duì)于上層應(yīng)用,IActivityManager不希望把所有的接口都暴露出來,因而使用ActivityManager作為中介來訪問IActivityManager提供的功能。ActivityManager是通過ActivityManagerNative.getDefault()來獲取到IActivityManager這個(gè)接口的。因?yàn)锳ctivityManager是運(yùn)行在用戶進(jìn)程的,因而getDefault()獲取的是ActivityManagerProxy.
2、com.android.server.am.ActivityManagerService
2.1 簡單類圖
QQ截圖20160706104100.png
對(duì)于使用過AIDL并且看過.aidl文件自動(dòng)生成的java類的人來說,這個(gè)不要太熟悉了,IActivityManager對(duì)應(yīng)自定義的接口,ActivityManagerNative對(duì)應(yīng)Stub,ActivityManagerProxy對(duì)應(yīng)Stub中的proxy,ActivityManagerService對(duì)應(yīng)的就是真正的接口實(shí)現(xiàn)者。
可以看到ActivityManagerService并不是一個(gè)SystemService,真正的SystemService是它里面的內(nèi)部類Lifecycle,而Lifecycle持有ActivityManagerService的實(shí)例并且其生命周期都是由ActivityManagerService來替代完成的。這樣設(shè)計(jì),一來使得ActivityManagerService具有SystemService具有的一切特征,二來可以向調(diào)用者比如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);}public void onStart() {// 啟動(dòng)該SystemServicemService.start();}public ActivityManagerService getService() {return mService;}}這里的Lifecycle是一個(gè)SystemService,內(nèi)部持有一個(gè)ActivityManagerService實(shí)例。
2.3 ActivityManagerService構(gòu)造函數(shù)
// 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.// 該構(gòu)造函數(shù)是運(yùn)行在主線程中的,其里面會(huì)有其他的子線程用來完成相關(guān)任務(wù)public ActivityManagerService(Context systemContext) {mContext = systemContext;//系統(tǒng)進(jìn)程中的ContextmFactoryTest = FactoryTest.getMode();// 系統(tǒng)進(jìn)程(framework-res.apk)對(duì)應(yīng)的ActivityThreadmSystemThread = ActivityThread.currentActivityThread();Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());// 創(chuàng)建了一個(gè)ServiceThread(HandlerThread)mHandlerThread = new ServiceThread(TAG,android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);mHandlerThread.start();// 創(chuàng)建一個(gè)Handler,使用的是ServiceThread的LoopermHandler = new MainHandler(mHandlerThread.getLooper());// 創(chuàng)建了一個(gè)UiHandler,它的Looper是mainLoopermUiHandler = 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);// 最近任務(wù)列表mRecentTasks = new RecentTasks(this);//mStackSupervisor = new ActivityStackSupervisor(this, mRecentTasks);//mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, mRecentTasks);mProcessCpuThread = new Thread("CpuTracker") {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.// 初始化系統(tǒng)進(jìn)程的Application并啟動(dòng)它mActivityManagerService.setSystemProcess(); public void setSystemProcess() {try {// 向ServiceManager中注冊(cè)各種服務(wù)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>標(biāo)簽解析出來的配置信息保存在這個(gè)對(duì)象中// 從PackageManagerService中獲取framework-res.apk安裝包的ApplicationInfo信息// 注意這里的使用方式,PackageManagerService和ActivityManagerService運(yùn)行在同一個(gè)進(jìn)程// 這里為什么要使用跨進(jìn)程的方式來進(jìn)行通信呢?// 原因是保持android環(huán)境中和服務(wù)交互的一致性,利于以后擴(kuò)展和維護(hù)ApplicationInfo info = mContext.getPackageManager().getApplicationInfo("android", STOCK_PM_FLAGS);// mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());synchronized (this) {// 生成保存系統(tǒng)進(jìn)程信息的對(duì)象ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);// 保持該進(jìn)程一直處于運(yùn)行狀態(tài)app.persistent = true;app.pid = MY_PID;app.maxAdj = ProcessList.SYSTEM_ADJ;// 給該進(jìn)程對(duì)象設(shè)置該進(jìn)程中AMS和其他進(jìn)程交互的接口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標(biāo)簽相關(guān)信息getSystemContext().installSystemApplicationInfo(info, classLoader);// give ourselves a default profilermProfiler = 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)對(duì)應(yīng)的ApplicationInfo信息,然后填充到apk對(duì)應(yīng)的LoadedApk對(duì)象中。從PackageManagerService分析中了解到在系統(tǒng)啟動(dòng)的時(shí)候會(huì)掃描并解析APK把信息保存到它自己的Map中,所以這里直接從這個(gè)map中直接取出來,然后從android系統(tǒng)Context初始化過程中知道,對(duì)于packagename為"android"的framework-res.apk,其ApplicationInfo在LoadedApk構(gòu)造函數(shù)中是直接new出來的,是一個(gè)空的對(duì)象,因而這里從PackageManagerService取出來填充到這里。
2.4.2 ActivityManagerservice.newProcessRecordLocked():創(chuàng)建一個(gè)ProcessRecord對(duì)象,用來保存系統(tǒng)進(jìn)程信息
final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess,boolean isolated, int isolatedUid) {// 進(jìn)程名String proc = customProcess != null ? customProcess : info.processName;// 耗電量統(tǒng)計(jì)BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();final int userId = UserHandle.getUserId(info.uid);int uid = info.uid;if (isolated) {// 對(duì)系統(tǒng)進(jìn)程該值為falseif (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;}}// 創(chuàng)建ProcessRecord,用于存儲(chǔ)系統(tǒng)進(jìn)程所在進(jìn)程的所有信息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簡要介紹
首先看類圖:
QQ截圖20160812181904.png
ApplicationThread具備IApplicationThread所有的能力,是AMS與其他應(yīng)用交互的橋梁,ActivityThread里面通過mAppThread屬性指向它。
以上,便是ActivityManagerservice.setSystemProcess()的主要工作:一是從PackageManagerService中找到系統(tǒng)APK(framework-res.apk)對(duì)應(yīng)的ApplicationInfo信息,填充到和它對(duì)應(yīng)的LoadedApk對(duì)象中;二是創(chuàng)建一個(gè)記錄其進(jìn)程信息的對(duì)象ProcessRecord并關(guān)聯(lián)IApplicationThread,使得該進(jìn)程中的AMS能夠和其他進(jìn)程進(jìn)行交互。
2.5 ActivityManagerService.installSystemProviders();
public final void installSystemProviders() {List<ProviderInfo> providers;synchronized (this) {// 獲取進(jìn)程名為"system",進(jìn)程 UID為1000的進(jìn)程// 在PMS的Settings中可以知道該進(jìn)程共享名為"android.uid.system"ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID);// 找到該進(jìn)程中的所有contentprovider對(duì)應(yīng)的信息ProviderInfoproviders = 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對(duì)ContentProvider進(jìn)行安裝mSystemThread.installSystemProviders(providers);}mCoreSettingsObserver = new CoreSettingsObserver(this);//mUsageStatsService.monitorPackages();}framework-res.apk中AndroidManifest.xml文件相關(guān)配置:
<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-filterandroid: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內(nèi)容
<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文件中可以發(fā)現(xiàn),frameworkwork-res.apk和SettingProvider都運(yùn)行在名為system的進(jìn)程中,在2.4中那個(gè)創(chuàng)建出來的ProcessRecord以及這里要找的ProcessRecord都是指向這個(gè)進(jìn)程,從清單文件中可以看到,framework-res.apk中是沒有provider的,只有settingprovider中有一個(gè),所以這里找到的就是settingprovider中的contentprovider對(duì)應(yīng)的信息ProviderInfo。
在查詢到了該進(jìn)程contentprovider對(duì)應(yīng)的信息后,通過ActivityThread的installSystemProviders()來對(duì)其進(jìn)行安裝。查詢的詳細(xì)過程和安裝的過程這里略過,這個(gè)暫時(shí)不是我的重點(diǎn)~~
2.6 ActivityManagerService.systemReady(Runnable callback)
這個(gè)方法主要作用是:
1)發(fā)送Intent.ACTION_PRE_BOOT_COMPLETED廣播,該廣播只會(huì)被處理一次,接受者接收該廣播主要是對(duì)數(shù)據(jù)庫做一些處理;
2)清理在啟動(dòng)過程中啟動(dòng)的非persistent進(jìn)程,persistent進(jìn)程是需要一直保持運(yùn)行的進(jìn)程;
3)讀取設(shè)置信息:需要調(diào)試的程序包名,等待調(diào)試的應(yīng)用,字體大小相關(guān)等等
4)加載資源信息
5)運(yùn)行回調(diào):允許觀察native crash了,啟動(dòng)SystemUI.apk等等其他服務(wù);
6)啟動(dòng)persistent應(yīng)用,啟動(dòng)Launcher.
2.7 Launcher啟動(dòng)過程
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對(duì)應(yīng)的IntentIntent intent = getHomeIntent();// 從PackageManagerService中取得Launcher對(duì)應(yīng)的信息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運(yùn)行進(jìn)程信息ProcessRecord app = getProcessRecordLocked(aInfo.processName,aInfo.applicationInfo.uid, true);// 如果Launcher沒有啟動(dòng),則啟動(dòng)它if (app == null || app.instrumentationClass == null) {//intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);//mStackSupervisor初始化在構(gòu)造函數(shù)中,啟動(dòng)LaunchermStackSupervisor.startHomeActivity(intent, aInfo, reason);}}return true;} 原文地址:?http://www.jianshu.com/p/abab3b44c6b0總結(jié)
以上是生活随笔為你收集整理的ActivityManagerService简要分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android后台杀死系列之三:LowM
- 下一篇: Android Service 形式分类