Android 系统启动流程分析之启动应用

继上一篇Android系统启动流程分析之安装应用文章接着分析系统启动应用的过程.

Android系统的启动流程简要分析里已经介绍了SystemServer在main方法里创建了一个线程ServerThread,并调用initAndLoop方法加载各种服务.

ActivityManagerService(Ams)就是在initAndLoop方法里加载的.那么,看下initAndLoop方法里关于AMS的核心代码.

1.context = ActivityManagerService.main(factoryTest);

2.ActivityManagerService.setSystemProcess();

3.ActivityManagerService.installSystemProviders();

4.ActivityManagerService.self().setWindowManager(wm);

5.ActivityManagerService.self().systemReady

一步一步进行分析.

1.context = ActivityManagerService.main(factoryTest);

这行代码是启动ActivityManagerService,获取上下文context,进入AMS的main方法看一下

public static final Context main(int factoryTest) {
		AThread thr = new AThread();
		thr.start();
		
		synchronized (thr) {
			while (thr.mService == null) {
				try {
					//线程等待activitymanagerservice初始化完成
					thr.wait();
				} catch (InterruptedException e) {
				}
			}
		}
		ActivityManagerService m = thr.mService;
		mSelf = m;
		//启动一个主线程
		ActivityThread at = ActivityThread.systemMain();
		
		mSystemThread = at;
		//获取上下文context
		Context context = at.getSystemContext();
		
		context.setTheme(android.R.style.Theme_Holo);
		m.mContext = context;
		m.mFactoryTest = factoryTest;
		m.mIntentFirewall = new IntentFirewall(m.new IntentFirewallInterface());

		//新建一个activity堆栈管理辅助类
		m.mStackSupervisor = new ActivityStackSupervisor(m, context, thr.mLooper);

		m.mBatteryStatsService.publish(context);
		m.mUsageStatsService.publish(context);
		m.mAppOpsService.publish(context);

		synchronized (thr) {
			thr.mReady = true;
			//activitymanagerservice启动完成
			thr.notifyAll();
		}

		m.startRunning(null, null, null, null);

		return context;
	}

1.1

在mian方法里会创建一个线程AThread,AThread用来初始化Looper,AThread等待ActivityManagerService初始化完成后把自己的成员变量mService赋值给ActivityManagerService自身.

1.2

启动一个主线程ActivityThread,ActivityThread是所有Application运行的主线程,

1.3

获取上下文context,最终是调用ContextImpl的createSystemContext方法返回的,context本质是ContextImpl的实例

1.4

等ActivityManagerService启动完成,调用m.startRunning()方法运行,在startRunning方法内部调用systemReady()方法.做系统准备工作.

public final void startRunning(String pkg, String cls, String action, String data) {
		synchronized (this) {
			if (mStartRunning) {
				return;
			}
			mStartRunning = true;
			mTopComponent = pkg != null && cls != null ? new ComponentName(pkg, cls) : null;
			//如果传入的action为空那么赋值Intent.ACTION_MAIN给mTopAction
			mTopAction = action != null ? action : Intent.ACTION_MAIN;
			mTopData = data;
			if (!mSystemReady) {
				return;
			}
		}

		systemReady(null);
	}

这个mTopAction就是后面要启动第一个Activity,也就是Launcher的Action.

1.4.1

在systemReady方法调用mStackSupervisor.resumeTopActivitiesLocked方法.

public void systemReady(final Runnable goingCallback){
			......
			......
			mStackSupervisor.resumeTopActivitiesLocked();
			......
	}	 

1.4.2

最终经过层层跳转会回到ActivityManagerService的startHomeActivityLocked方法.

boolean startHomeActivityLocked(int userId) {
		......
		......
		//获取intent信息
		Intent intent = getHomeIntent();
		
		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);
			ProcessRecord app = getProcessRecordLocked(aInfo.processName, aInfo.applicationInfo.uid, true);
			if (app == null || app.instrumentationClass == null) {
				intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
				//启动主程序,也就是Laucnher
				mStackSupervisor.startHomeActivity(intent, aInfo);
			}
		}
		return true;
	}

1.4.3

通过getHomeIntent方法获取Intent信息,看下代码

Intent getHomeIntent() {
		Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
		intent.setComponent(mTopComponent);
		if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
			//设置Category
			intent.addCategory(Intent.CATEGORY_HOME);
		}
		return intent;
	}

给intent设置了Category,这个mTopAction就是前面设置的.

那么在这里Intent指定Action为action.MAIN,category为category.HOME.这正是启动Launcher的配置


     
      
       
      
     
    

1.4.4

回到1.4.2,调用如下代码启动Launcher

//启动主程序,也就是Laucnher
mStackSupervisor.startHomeActivity(intent, aInfo);

2.ActivityManagerService.setSystemProcess()

这个方法是用来注册一些服务和获取、绑定进程信息的.

public static void setSystemProcess() {
		try {
			ActivityManagerService m = mSelf;
			//注册ActivityManagerService
			ServiceManager.addService(Context.ACTIVITY_SERVICE, m, true);
			//注册进程统计服务
			ServiceManager.addService(ProcessStats.SERVICE_NAME, m.mProcessStats);
			//注册内存服务
			ServiceManager.addService("meminfo", new MemBinder(m));
			//注册图像处理服务
			ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
			//注册数据库服务
			ServiceManager.addService("dbinfo", new DbBinder(m));
			//注册cpu服务
			if (MONITOR_CPU_USAGE) {
				ServiceManager.addService("cpuinfo", new CpuBinder(m));
			}
			//注册权限服务
			ServiceManager.addService("permission", new PermissionController(m));
			//获取应用信息
			ApplicationInfo info = mSelf.mContext.getPackageManager().getApplicationInfo("android", STOCK_PM_FLAGS);
			//绑定系统应用信息,
			mSystemThread.installSystemApplicationInfo(info);

			synchronized (mSelf) {
				//获取ProcessRecord实例,ProcessRecord是描述进程信息的
				ProcessRecord app = mSelf.newProcessRecordLocked(info, info.processName, false);
				app.persistent = true;
				app.pid = MY_PID;
				app.maxAdj = ProcessList.SYSTEM_ADJ;
				//调用ProcessStatsService开始记录process的状态
				app.makeActive(mSystemThread.getApplicationThread(), mSelf.mProcessStats);
				//把进程名,uid,ProcessRecord实例存到mProcessNames数组中
				mSelf.mProcessNames.put(app.processName, app.uid, app);
				synchronized (mSelf.mPidsSelfLocked) {
					mSelf.mPidsSelfLocked.put(app.pid, app);
				}
				mSelf.updateLruProcessLocked(app, false, null);
				mSelf.updateOomAdjLocked();
			}
		} catch (PackageManager.NameNotFoundException e) {
			throw new RuntimeException("Unable to find android system package", e);
		}
	}

2.1

在ServiceManager里注册一些服务,AMS、进程统计服务、内存服务、图像处理服务、数据库服务、CPU服务、权限服务

2.2

通过PackageManager获取应用信息

//获取应用信息
ApplicationInfo info = mSelf.mContext.getPackageManager().getApplicationInfo("android", STOCK_PM_FLAGS);

获取包名为android的apk的信息,对应的就是framework-res.apk.

2.3

调用以下代码将获取到的应用信息绑定到mSystemThread的context上.

mSystemThread.installSystemApplicationInfo(info);

2.4

ActivityManagerService调用newProcessRecordLocked方法创建一个ProcessRecord对象,ProcessRecord纪录了一个进程的信息,这里是指systemServer进程

3.ActivityManagerService.installSystemProviders();

这个方法是启动SettingsProvider的.SettingsProvider相当于系统的一个数据库.

4.ActivityManagerService.self().setWindowManager(wm);

这个方法是用来设置窗口管理器的.

5.ActivityManagerService.self().systemReady

这个方法是用来做系统准备工作的.

ActivityManagerService.self().systemReady(new Runnable() {
			public void run() {
				Slog.i(TAG, "Making services ready");
				try {
					// 开始监视native是否crash
					ActivityManagerService.self().startObservingNativeCrashes();
				} catch (Throwable e) {
					reportWtf("observing native crashes", e);
				}
				if (!headless) {
					//启动SystemUi
					startSystemUi(contextF);
				}
				try {
					if (mountServiceF != null)
						mountServiceF.systemReady();
				} catch (Throwable e) {
					reportWtf("making Mount Service ready", e);
				}
				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);
				}
				......
				......

5.1

开始监视native是否crash

5.2

启动SystemUi

5.3

做各种服务的准备工作,比如挂载管理服务、电脑管理服务、网络连接管理服务.

结束语:按照上述5大步来就可以慢慢理清启动应用的流程了.具体细节你们可以自己去探索.

    原文作者:ActivityManagerService
    原文地址: https://juejin.im/entry/576d650b128fe1005a21d9df
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞