ActivityManagerService服务线程启动源码分析【转】
本文转载自:http://blog.csdn.net/yangwen123/article/details/8177702
Android系统服务线程都驻留在SystemServer进程中,由SystemServer启动,在SystemServer.init2函数中,通过启动一个线程来启动各种系统服务线程。
- 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函数中启动:
- 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)
- 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线程
- 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实例
- public static final ActivityThread systemMain() {
- HardwareRenderer.disable(true);
- ActivityThread thread = new ActivityThread();
- thread.attach(true);
- return thread;
- }
- 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实例
- 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服务
- 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服务
- public void publish(Context context) {
- mContext = context;
- ServiceManager.addService(SERVICE_NAME, asBinder());
- }
⑥调用startRunning函数startRunning(null, null, null, null)
- 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=null
- mTopData = data;
- if (!mSystemReady) {
- return;
- }
- }
- systemReady(null);
- }
- 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()
- 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()
- 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服务线程启动源码分析【转】的更多相关文章
- Netty源码分析 (三)----- 服务端启动源码分析
本文接着前两篇文章来讲,主要讲服务端类剩下的部分,我们还是来先看看服务端的代码 /** * Created by chenhao on 2019/9/4. */ public final class ...
- Netty之旅三:Netty服务端启动源码分析,一梭子带走!
Netty服务端启动流程源码分析 前记 哈喽,自从上篇<Netty之旅二:口口相传的高性能Netty到底是什么?>后,迟迟两周才开启今天的Netty源码系列.源码分析的第一篇文章,下一篇我 ...
- RocketMQ中Broker的启动源码分析(一)
在RocketMQ中,使用BrokerStartup作为启动类,相较于NameServer的启动,Broker作为RocketMQ的核心可复杂得多 [RocketMQ中NameServer的启动源码分 ...
- RocketMQ中Broker的启动源码分析(二)
接着上一篇博客 [RocketMQ中Broker的启动源码分析(一)] 在完成准备工作后,调用start方法: public static BrokerController start(Broker ...
- RocketMQ中PullConsumer的启动源码分析
通过DefaultMQPullConsumer作为默认实现,这里的启动过程和Producer很相似,但相比复杂一些 [RocketMQ中Producer的启动源码分析] DefaultMQPullCo ...
- java多线程----线程池源码分析
http://www.cnblogs.com/skywang12345/p/3509954.html 线程池示例 在分析线程池之前,先看一个简单的线程池示例. 1 import java.util.c ...
- Netty 心跳服务之 IdleStateHandler 源码分析
前言:Netty 提供的心跳介绍 Netty 作为一个网络框架,提供了诸多功能,比如我们之前说的编解码,Netty 准备很多现成的编解码器,同时,Netty 还为我们准备了网络中,非常重要的一个服务- ...
- Django如何启动源码分析
Django如何启动源码分析 启动 我们启动Django是通过python manage.py runsever的命令 解决 这句话就是执行manage.py文件,并在命令行发送一个runsever字 ...
- Netty服务端的启动源码分析
ServerBootstrap的构造: public class ServerBootstrap extends AbstractBootstrap<ServerBootstrap, Serve ...
随机推荐
- Codeforces Gym101502 F.Building Numbers-前缀和
F. Building Numbers time limit per test 3.0 s memory limit per test 256 MB input standard input ou ...
- 洛谷——P2706 巧克力
P2706 巧克力 题目背景 王7的生日到了,他的弟弟准备送他巧克力. 题目描述 有一个被分成n*m格的巧克力盒,在(i,j)的位置上有a[i,j]块巧克力.就在送出它的前一天晚上,有老鼠夜袭巧克力盒 ...
- 小W计树
排列组合思想. 先跑一遍最短路, 再从1节点开始搜索, 假如搜到一个点的路径长度等于最短路, 则记录到达该点的路径数 + 1. 最后遍历一遍, ans *= rec[i] 输出答案即可. 关键在于想到 ...
- 【spring cloud】spring cloud子module的pom文件添加依赖,出现unknown问题【maven】
spring cloud项目,一般都是父项目中有多个子服务,也就是子module模块. 如下图: 问题描述:在父项目中引用了常用的jar包,例如,引入了spring boot的依赖,那么在子项目中引入 ...
- 【报错】spring整合activeMQ,pom.xml文件缺架包,启动报错:Caused by: java.lang.ClassNotFoundException: org.apache.xbean.spring.context.v2.XBeanNamespaceHandler
spring版本:4.3.13 ActiveMq版本:5.15 ======================================================== spring整合act ...
- iOS -- SKPhysicsJointSpring类
SKPhysicsJointSpring类 继承自 NSObject 符合 NSCoding(SKPhysicsJoint)NSObject(NSObject) 框架 /System/Library ...
- FreeBSD 8
FreeBSD 8.0的安装过程和7.2区别不大.先在FreeBSD官方网站上下载安装镜像,我一般都下载DVD的ISO,也有人爱好下最小的安装包,然后通过FTP或HTTP方式从网上下载各个程序包. 这 ...
- vdWebControl.js去水印
vdWebControl.js可以在浏览器中展示cad图形(须要使用其自家的转换工具把cad转换为vds格式.工具免费,但转换完成后的文件带水印信息),支持编辑图形. vdWebControl.js试 ...
- 微信小程序日期定位弹出框遮挡问题
只需要用bindtap绑定一个点击后的操作(隐藏键盘): wx.hideKeyboard()
- Solaris网络基础
划分子网: 把大网缩小为若干个小网.修改子网掩码,划分多个网络. 那么如何确定子网的子网掩码和IP地址? 以上你会发现少了6个IP. Ifconfig e1000g0 down down掉网卡 ...