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 簡單類圖
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);}public void onStart() {// 啟動該SystemServicemService.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;//系統進程中的ContextmFactoryTest = FactoryTest.getMode();// 系統進程(framework-res.apk)對應的ActivityThreadmSystemThread = 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的LoopermHandler = new MainHandler(mHandlerThread.getLooper());// 創建了一個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);// 最近任務列表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.// 初始化系統進程的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 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)對應的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) {// 對系統進程該值為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;}}// 創建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簡要介紹
首先看類圖:
QQ截圖20160812181904.png
ApplicationThread具備IApplicationThread所有的能力,是AMS與其他應用交互的橋梁,ActivityThread里面通過mAppThread屬性指向它。
以上,便是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對應的信息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對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-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內容
<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對應的IntentIntent 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初始化在構造函數中,啟動LaunchermStackSupervisor.startHomeActivity(intent, aInfo, reason);}}return true;} 原文地址:?http://www.jianshu.com/p/abab3b44c6b0總結
以上是生活随笔為你收集整理的ActivityManagerService简要分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android后台杀死系列之三:LowM
- 下一篇: 进程间通信--IPC