首页 > 代码库 > ActivityManagerService服务线程启动源码分析【转】
ActivityManagerService服务线程启动源码分析【转】
本文转载自:http://blog.csdn.net/yangwen123/article/details/8177702
Android系统服务线程都驻留在SystemServer进程中,由SystemServer启动,在SystemServer.init2函数中,通过启动一个线程来启动各种系统服务线程。
[java] view plain copy
- public static final void init2() {
- Slog.i(TAG, "Entered the Android system server!");
- Thread thr = new ServerThread();// 创建一个线程
- thr.setName("android.server.ServerThread");//设置线程名称
- thr.start();/启动该线程
- }
android系统服务都是在thr线程的run函数中启动:
[java] view plain copy
- public void run() {
- EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,SystemClock.uptimeMillis());
- Looper.prepare();//创建一个消息循环对象
- android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);
- BinderInternal.disableBackgroundScheduling(true);
- android.os.Process.setCanSelfBackground(false);
- // Critical services...
- try {
- Slog.i(TAG, "Activity Manager");
- //①启动ActivityManagerService服务线程
- context = ActivityManagerService.main(factoryTest);
- ................................................
- //②向ServiceManager注册自己
- ActivityManagerService.setSystemProcess();
- ................................................
- Slog.i(TAG, "System Content Providers");
- //③安装系统Providers
- ActivityManagerService.installSystemProviders();
- ................................................
- //④设置ActivityManagerService的成员变量mWindowManager
- ActivityManagerService.self().setWindowManager(wm);
- ................................................
- } catch (RuntimeException e) {
- Slog.e("System", "******************************************");
- Slog.e("System", "************ Failure starting core service", e);
- }
- //⑤调用systemReady函数为系统准备各种服务
- ActivityManagerService.self().systemReady(new Runnable() {
- public void run() {
- Slog.i(TAG, "Making services ready");
- startSystemUi(contextF);
- try {
- if (batteryF != null) batteryF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Battery Service ready", e);
- }
- try {
- if (networkManagementF != null) networkManagementF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Network Managment Service ready", e);
- }
- try {
- if (networkStatsF != null) networkStatsF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Network Stats Service ready", e);
- }
- try {
- if (networkPolicyF != null) networkPolicyF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Network Policy Service ready", e);
- }
- try {
- if (connectivityF != null) connectivityF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Connectivity Service ready", e);
- }
- try {
- if (dockF != null) dockF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Dock Service ready", e);
- }
- try {
- if (usbF != null) usbF.systemReady();
- } catch (Throwable e) {
- reportWtf("making USB Service ready", e);
- }
- try {
- if (uiModeF != null) uiModeF.systemReady();
- } catch (Throwable e) {
- reportWtf("making UI Mode Service ready", e);
- }
- try {
- if (recognitionF != null) recognitionF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Recognition Service ready", e);
- }
- Watchdog.getInstance().start();
- // It is now okay to let the various system services start their
- // third party code...
- try {
- if (appWidgetF != null) appWidgetF.systemReady(safeMode);
- } catch (Throwable e) {
- reportWtf("making App Widget Service ready", e);
- }
- try {
- if (wallpaperF != null) wallpaperF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Wallpaper Service ready", e);
- }
- try {
- if (immF != null) immF.systemReady(statusBarF);
- } catch (Throwable e) {
- reportWtf("making Input Method Service ready", e);
- }
- try {
- if (locationF != null) locationF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Location Service ready", e);
- }
- try {
- if (countryDetectorF != null) countryDetectorF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Country Detector Service ready", e);
- }
- try {
- if (throttleF != null) throttleF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Throttle Service ready", e);
- }
- try {
- if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Network Time Service ready", e);
- }
- try {
- if (textServiceManagerServiceF != null) textServiceManagerServiceF.systemReady();
- } catch (Throwable e) {
- reportWtf("making Text Services Manager Service ready", e);
- }
- }
- });
- Looper.loop();
- Slog.d(TAG, "System ServerThread is exiting!");
- }
第一:ActivityManagerService.main(factoryTest)
[java] view plain copy
- public static final Context main(int factoryTest) {
- //①启动AThread线程来创建ActivityManagerService实例
- AThread thr = new AThread();
- thr.start();
- synchronized (thr) {
- while (thr.mService == null) {
- try {
- thr.wait();
- } catch (InterruptedException e) {
- }
- }
- }
- //将创建的ActivityManagerService实例保存到ActivityManagerService的静态变量mSelf
- ActivityManagerService m = thr.mService;
- mSelf = m;
- //②创建ActivityThread实例并保存到ActivityManagerService的静态变量mSystemThread
- ActivityThread at = ActivityThread.systemMain();
- mSystemThread = at;
- Context context = at.getSystemContext();
- context.setTheme(android.R.style.Theme_Holo);
- m.mContext = context;
- m.mFactoryTest = factoryTest;
- //③创建一个ActivityStack实例,并保存到ActivityManagerService的成员变量mMainStack中
- m.mMainStack = new ActivityStack(m, context, true);
- //④向ServiceManager注册BatteryStatsService服务
- m.mBatteryStatsService.publish(context);
- //⑤向ServiceManager注册UsageStatsService服务
- m.mUsageStatsService.publish(context);
- synchronized (thr) {
- //取消AThread线程等待,进入消息循环状态
- thr.mReady = true;
- thr.notifyAll();
- }
- //⑥调用startRunning函数
- m.startRunning(null, null, null, null);
- return context;
- }
①启动AThread线程
[java] view plain copy
- static class AThread extends Thread {
- ActivityManagerService mService;
- boolean mReady = false;
- public AThread() {
- super("ActivityManager");
- }
- public void run() {
- //创建消息循环对象
- Looper.prepare();
- android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);
- android.os.Process.setCanSelfBackground(false);
- ActivityManagerService m = new ActivityManagerService();
- synchronized (this) {
- //创建ActivityManagerService实例
- mService = m;
- notifyAll();
- }
- //mReady = false,所以该线程处于等待
- synchronized (this) {
- while (!mReady) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- }
- // For debug builds, log event loop stalls to dropbox for analysis.
- if (StrictMode.conditionallyEnableDebugLogging()) {
- Slog.i(TAG, "Enabled StrictMode logging for AThread‘s Looper");
- }
- //开启该线程的消息循环
- Looper.loop();
- }
- }
②创建ActivityThread实例
[java] view plain copy
- public static final ActivityThread systemMain() {
- HardwareRenderer.disable(true);
- ActivityThread thread = new ActivityThread();
- thread.attach(true);
- return thread;
- }
[java] view plain copy
- private void attach(boolean system) {
- //本地线程存储
- sThreadLocal.set(this);
- mSystemThread = system;//mSystemThread=true
- if (!system) {
- ViewRootImpl.addFirstDrawHandler(new Runnable() {
- public void run() {
- ensureJitEnabled();
- }
- });
- android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
- RuntimeInit.setApplicationObject(mAppThread.asBinder());
- IActivityManager mgr = ActivityManagerNative.getDefault();
- try {
- mgr.attachApplication(mAppThread);
- } catch (RemoteException ex) {
- // Ignore
- }
- } else {
- // Don‘t set application object here -- if the system crashes,
- // we can‘t display an alert, we just want to die die die.
- android.ddm.DdmHandleAppName.setAppName("system_process");
- try {
- mInstrumentation = new Instrumentation();
- ContextImpl context = new ContextImpl();
- context.init(getSystemContext().mPackageInfo, null, this);
- //创建Application实例,并保存在成员变量mAllApplications中
- Application app = Instrumentation.newApplication(Application.class, context);
- mAllApplications.add(app);
- mInitialApplication = app;
- //调用应用程序的onCreate函数
- app.onCreate();
- } catch (Exception e) {
- throw new RuntimeException(
- "Unable to instantiate Application():" + e.toString(), e);
- }
- }
- ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
- public void onConfigurationChanged(Configuration newConfig) {
- synchronized (mPackages) {
- // We need to apply this change to the resources
- // immediately, because upon returning the view
- // hierarchy will be informed about it.
- if (applyConfigurationToResourcesLocked(newConfig, null)) {
- // This actually changed the resources! Tell
- // everyone about it.
- if (mPendingConfiguration == null ||
- mPendingConfiguration.isOtherSeqNewer(newConfig)) {
- mPendingConfiguration = newConfig;
- queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
- }
- }
- }
- }
- public void onLowMemory() {
- }
- public void onTrimMemory(int level) {
- }
- });
- }
③创建一个ActivityStack实例
[java] view plain copy
- ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
- mService = service;
- mContext = context;
- mMainStack = mainStack;
- PowerManager pm =(PowerManager)context.getSystemService(Context.POWER_SERVICE);
- mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
- mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
- mLaunchingActivity.setReferenceCounted(false);
- }
④注册BatteryStatsService服务
[java] view plain copy
- public void publish(Context context) {
- mContext = context;
- ServiceManager.addService("batteryinfo", asBinder());
- mStats.setNumSpeedSteps(new PowerProfile(mContext).getNumSpeedSteps());
- mStats.setRadioScanningTimeout(mContext.getResources().getInteger(
- com.android.internal.R.integer.config_radioScanningTimeout)* 1000L);
- }
⑤注册UsageStatsService服务
[java] view plain copy
- public void publish(Context context) {
- mContext = context;
- ServiceManager.addService(SERVICE_NAME, asBinder());
- }
⑥调用startRunning函数startRunning(null, null, null, null)
[java] view plain copy
- public final void startRunning(String pkg, String cls, String action,String data) {
- synchronized(this) {
- //mStartRunning = false
- if (mStartRunning) {
- return;
- }
- mStartRunning = true;
- //mTopComponent=null
- mTopComponent = pkg != null && cls != null? new ComponentName(pkg, cls) : null;
- //mTopAction=Intent.ACTION_MAIN
- mTopAction = action != null ? action : Intent.ACTION_MAIN;
- //mTopData=http://www.mamicode.com/null
- mTopData = data;
- if (!mSystemReady) {
- return;
- }
- }
- systemReady(null);
- }
[java] view plain copy
- public void systemReady(final Runnable goingCallback) {
- //goingCallback = null
- synchronized(this) {
- //mSystemReady = false
- if (mSystemReady) {
- if (goingCallback != null) goingCallback.run();
- return;
- }
- // mDidUpdate = false
- if (!mDidUpdate) {
- if (mWaitingUpdate) {
- return;
- }
- Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
- List<ResolveInfo> ris = null;
- try {
- ris = AppGlobals.getPackageManager().queryIntentReceivers(intent, null, 0);
- } catch (RemoteException e) {
- }
- if (ris != null) {
- for (int i=ris.size()-1; i>=0; i--) {
- if ((ris.get(i).activityInfo.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
- ris.remove(i);
- }
- }
- intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
- ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
- final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
- for (int i=0; i<ris.size(); i++) {
- ActivityInfo ai = ris.get(i).activityInfo;
- ComponentName comp = new ComponentName(ai.packageName, ai.name);
- if (lastDoneReceivers.contains(comp)) {
- ris.remove(i);
- i--;
- }
- }
- for (int i=0; i<ris.size(); i++) {
- ActivityInfo ai = ris.get(i).activityInfo;
- ComponentName comp = new ComponentName(ai.packageName, ai.name);
- doneReceivers.add(comp);
- intent.setComponent(comp);
- IIntentReceiver finisher = null;
- if (i == ris.size()-1) {
- finisher = new IIntentReceiver.Stub() {
- public void performReceive(Intent intent, int resultCode,
- String data, Bundle extras, boolean ordered,
- boolean sticky) {
- // The raw IIntentReceiver interface is called
- // with the AM lock held, so redispatch to
- // execute our code without the lock.
- mHandler.post(new Runnable() {
- public void run() {
- synchronized (ActivityManagerService.this) {
- mDidUpdate = true;
- }
- writeLastDonePreBootReceivers(doneReceivers);
- showBootMessage(mContext.getText(
- R.string.android_upgrading_complete),false);
- systemReady(goingCallback);
- }
- });
- }
- };
- }
- Slog.i(TAG, "Sending system update to: " + intent.getComponent());
- broadcastIntentLocked(null, null, intent, null, finisher,
- 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
- if (finisher != null) {
- mWaitingUpdate = true;
- }
- }
- }
- if (mWaitingUpdate) {
- return;
- }
- mDidUpdate = true;
- }
- mSystemReady = true;
- if (!mStartRunning) {
- return;
- }
- }
- 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;
- }
- Slog.i(TAG, "System now ready");
- EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,SystemClock.uptimeMillis());
- synchronized(this) {
- // Make sure we have no pre-ready processes sitting around.
- if (mFactoryTest == SystemServer.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_MSG;
- msg.getData().putCharSequence("msg", errorMsg);
- mHandler.sendMessage(msg);
- }
- }
- }
- retrieveSettings();
- if (goingCallback != null) goingCallback.run();
- synchronized (this) {
- if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
- try {
- List apps = AppGlobals.getPackageManager().getPersistentApplications(STOCK_PM_FLAGS);
- if (apps != null) {
- int N = apps.size();
- int i;
- for (i=0; i<N; i++) {
- ApplicationInfo info= (ApplicationInfo)apps.get(i);
- if (info != null &&!info.packageName.equals("android")) {
- addAppLocked(info);
- }
- }
- }
- } catch (RemoteException ex) {
- // pm is in same process, this will never happen.
- }
- }
- // Start up initial activity.
- mBooting = true;
- try {
- if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
- Message msg = Message.obtain();
- msg.what = SHOW_UID_ERROR_MSG;
- mHandler.sendMessage(msg);
- }
- } catch (RemoteException e) {
- }
- mMainStack.resumeTopActivityLocked(null);
- }
- }
第二:ActivityManagerService.setSystemProcess()
[java] view plain copy
- public static void setSystemProcess() {
- try {
- ActivityManagerService m = mSelf;
- ServiceManager.addService("activity", m);
- ServiceManager.addService("meminfo", new MemBinder(m));
- ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
- if (MONITOR_CPU_USAGE) {
- ServiceManager.addService("cpuinfo", new CpuBinder(m));
- }
- ServiceManager.addService("permission", new PermissionController(m));
- //把应用程序框架层下面的android包加载进来
- ApplicationInfo info =mSelf.mContext.getPackageManager().getApplicationInfo("android", STOCK_PM_FLAGS);
- mSystemThread.installSystemApplicationInfo(info);
- synchronized (mSelf) {
- ProcessRecord app = mSelf.newProcessRecordLocked(
- mSystemThread.getApplicationThread(), info,info.processName);
- app.persistent = true;
- app.pid = MY_PID;
- app.maxAdj = ProcessList.SYSTEM_ADJ;
- mSelf.mProcessNames.put(app.processName, app.info.uid, app);
- synchronized (mSelf.mPidsSelfLocked) {
- mSelf.mPidsSelfLocked.put(app.pid, app);
- }
- mSelf.updateLruProcessLocked(app, true, true);
- }
- } catch (PackageManager.NameNotFoundException e) {
- throw new RuntimeException(
- "Unable to find android system package", e);
- }
- }
第三:ActivityManagerService.installSystemProviders()
[java] view plain copy
- public static final void installSystemProviders() {
- List<ProviderInfo> providers;
- synchronized (mSelf) {
- ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
- providers = mSelf.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) {
- mSystemThread.installSystemProviders(providers);
- }
- mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
- mSelf.mUsageStatsService.monitorPackages();
- }
第三:ActivityManagerService.systemReady()
ActivityManagerService服务线程启动源码分析【转】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。