SystemServer第三个启动的是ActivityManagerService
本文参考http://blog.csdn.net/lilian0118/article/details/26561835
(frameworks/base/services/java/com/android/server/SystemServer.java)
@Override
public void run() {
….
Slog.i(TAG, "Activity Manager");
context = ActivityManagerService.main(factoryTest);
….
ActivityManagerService.setSystemProcess();
…..
Slog.i(TAG, "System Content Providers");
ActivityManagerService.installSystemProviders();
….
ActivityManagerService.self().setWindowManager(wm);
ActivityManagerService.self().systemReady(new Runnable() {
public void run() {
Slog.i(TAG, "Making services ready");
try {
ActivityManagerService.self().startObservingNativeCrashes(); // 开始监视native是否crash
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
if (!headless) startSystemUi(contextF);
try {
if (mountServiceF != null) mountServiceF.systemReady();
} catch (Throwable e) {
reportWtf("making Mount Service ready", e);
}
...}
};
}
可以看出ActivityManagerService还跟SystemProvider和WindowManager有关系
先看
context = ActivityManagerService.main(factoryTest);
public static final Context main(int factoryTest) {
AThread thr = new AThread();
thr.start();
synchronized (thr) {
while (thr.mService == null) {
try {
thr.wait();
} catch (InterruptedException e) {
}
}
}
ActivityManagerService m = thr.mService;
mSelf = m;
ActivityThread at = ActivityThread.systemMain();
mSystemThread = at;
Context context = at.getSystemContext();
context.setTheme(android.R.style.Theme_Holo);
m.mContext = context;
m.mFactoryTest = factoryTest;
m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
m.mIntentFirewall = new IntentFirewall(m.new IntentFirewallInterface());
m.mBatteryStatsService.publish(context);
m.mUsageStatsService.publish(context);
m.mAppOpsService.publish(context);
synchronized (thr) {
thr.mReady = true;
thr.notifyAll();
}
m.startRunning(null, null, null, null);
return context;
}
我们一行一行代码来分析
AThread thr = new AThread();
thr.start();
synchronized (thr) {
while (thr.mService == null) {
try {
thr.wait();
} catch (InterruptedException e) {
}
}
}
ActivityManagerService m = thr.mService;
mSelf = m;
首先创建了AThread对象,然后等待Athread创建thr.mService成功,如果创建不成功就一直等待
static class AThread extends Thread {
ActivityManagerService mService;
Looper mLooper;
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) {
mService = m;
mLooper = Looper.myLooper();
notifyAll();
}
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();
}
}
在Athread里面创建一个ActivityManagerService对象
private ActivityManagerService() {
Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT); // 创建foregroud BroadcastQueue 用于广播
mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT); // 创建backgroud BroadcastQueue 用于广播
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
mServices = new ActiveServices(this); // 用于Service
mProviderMap = new ProviderMap(this);// 用于记录contentprovider的authority和class
File dataDir = Environment.getDataDirectory(); // init.rc 中是/data
File systemDir = new File(dataDir, "system"); // data/system
systemDir.mkdirs();
mBatteryStatsService = new BatteryStatsService(new File(
systemDir, "batterystats.bin").toString());// data/system/battrtstats.bin 收集影响电池的信息
mBatteryStatsService.getActiveStatistics().readLocked();
mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
mOnBattery = DEBUG_POWER ? true
: mBatteryStatsService.getActiveStatistics().getIsOnBattery();
mBatteryStatsService.getActiveStatistics().setCallback(this);
mUsageStatsService = new UsageStatsService(new File(
systemDir, "usagestats").toString()); // 收集各个组件使用情况 // data/system/usagesstats
mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"));
//权限管理 data/system/ appops.xml
mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0")); // 对后面开启launcher有作用
// User 0 is the first and only user that runs at boot.
mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
mUserLru.add(Integer.valueOf(0));
updateStartedUserArrayLocked();
GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
mConfiguration.setToDefaults();
mConfiguration.setLocale(Locale.getDefault());
mConfigurationSeq = mConfiguration.seq = 1;
mProcessStats.init(); // 初始化用于收集进程信息的
// data/system/ packages-compat.xml
mCompatModePackages = new CompatModePackages(this, systemDir);
// Add ourself to the Watchdog monitors.
Watchdog.getInstance().addMonitor(this); // watchdog 监视
mProcessStatsThread = new Thread("ProcessStats") {
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) {
mProcessStatsMutexFree.set(true);
this.wait(nextCpuDelay);
}
}
} catch (InterruptedException e) {
}
updateCpuStatsNow();
} catch (Exception e) {
Slog.e(TAG, "Unexpected exception collecting process stats", e);
}
}
}
};
mProcessStatsThread.start(); // 开启线程监视cpu状况
}
而ActivityManager完成如上操作,创建了用于广播的BroadcastQueue,用于Service的ActiveService,
http://blog.csdn.net/z642010820/article/details/7341469,
用于收集各个组件使用情况的UsageStatsService,
用于权限管理的AppOpsService
(http://blog.mssun.me/security/android-4-3-app-ops-analysis/)
用于package 兼容的CompatModePackages
还有监视CPU状态的thread
做完了初始化工作,Athread notify,执行
ActivityThread at = ActivityThread.systemMain();
mSystemThread = at;
我们看看systemMain做了什么
public static ActivityThread systemMain() {
HardwareRenderer.disable(true); // 把硬件渲染禁掉
ActivityThread thread = new ActivityThread(); // 创建ActivityThread
thread.attach(true);
return thread;
}
private void attach(boolean system) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) { // 如果不是系统
ViewRootImpl.addFirstDrawHandler(new Runnable() {
public void run() {
ensureJitEnabled();
}
}); // 增加FirstDrawHandler
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder()); // 设置ApplicationThread,RuntimeInit是runtime初始化主入口
IActivityManager mgr = ActivityManagerNative.getDefault(); // 获取并设置默认的ActivityManager
try {
mgr.attachApplication(mAppThread);// 设置appThread
} 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",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation(); // 创建Instrumentation
ContextImpl context = new ContextImpl(); // 创建系统Context实例
context.init(getSystemContext().mPackageInfo, null, this);// 初始化context
Application app = Instrumentation.newApplication(Application.class, context); //创建APP并CONTEXT设置到APP里面
mAllApplications.add(app); // 把app加入应用程序列表
mInitialApplication = app;
app.onCreate(); // 回调app的onCreate
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
// add dropbox logging to libcore
DropBox.setReporter(new DropBoxReporter());
// 增加config改变的callback,一旦有改变,则发送CONFIGURATION_CHANGED
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) {
}
});
}
在这一步走的system,创建Instrumentation,创建系统Context实例,初始化context,
创建APP并CONTEXT设置到APP里面,把app加入应用程序列表,回调app的onCreate,
增加config改变的callback,一旦有改变,则发送CONFIGURATION_CHANGED
在里面有个比较重要
context.init(getSystemContext().mPackageInfo, null, this);
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
ContextImpl context =
ContextImpl.createSystemContext(this); //创建systemcontext
LoadedApk info = new LoadedApk(this, "android", context, null,
CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
context.init(info, null, this); // context初始化info,res,asset,dm,configuration
context.getResources().updateConfiguration(
getConfiguration(), getDisplayMetricsLocked(
Display.DEFAULT_DISPLAY,
CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO));
mSystemContext = context;
//Slog.i(TAG, "Created system resources " + context.getResources()
// + ": " + context.getResources().getConfiguration());
}
}
return mSystemContext;
}
可以看到创建了一个systemcontext,而且loadapk与context关系,起关系图如下
接着看看ActivityStack
m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
ActivityStack(ActivityManagerService service, Context context, boolean mainStack, Looper looper) {
mHandler = new ActivityStackHandler(looper);// 创建ActivityStack消息处理
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); // 设置为不需要计数
}
从上面可知,创建了ActivityStack消息处理的handle回调,初始化变量,还有电管管理,而ActivityStackHandler主要处理SLEEP_TIMEOUT_MSG,PAUSE_TIMEOUT_MSG,IDLE_TIMEOUT_MSG,LAUNCH_TICK_MSG,DESTROY_TIMEOUT_MSG,IDLE_NOW_MSG,
LAUNCH_TIMEOUT_MSG,RESUME_TOP_ACTIVITY_MSG,STOP_TIMEOUT_MSG,DESTROY_ACTIVITIES_MSG等
继续看main函数
m.mIntentFirewall = new IntentFirewall(m.new IntentFirewallInterface());
m.mBatteryStatsService.publish(context);
m.mUsageStatsService.publish(context);
m.mAppOpsService.publish(context);
主要创建IntentFirewall,而IntentFirewall从/data/system/ifw/ifw.xml or /data/secure/system/ifw/ifw.xml读取出来activity,broadcast,service,并时刻监听着文件是否改变 ,而IntentFirewallInterface则是看是否是ActivityManagerService的进程id
而下面BatteryStatsService,UsageStatsService,AppOpsService.则是把服务注册掉binder manager
接着继续分析main
m.startRunning(null, null, null, null);
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; // 带进来的是null,所以没创建
mTopAction = action != null ? action : Intent.ACTION_MAIN; // 带进来是null,所以是Intent.ACTION_MAIN
mTopData = data; // 为null
if (!mSystemReady) { // 为false ,返回
return;
}
}
systemReady(null);//
}
因为带入的参数都是null,所以只是设置了mTopAction为Intent.ACTION_MAIN,mTopData为null,而mSystemReady为false,
第一步就结束跟踪到这里,ActivityManagerService main函数跑完,回到systemserver
Slog.i(TAG, "Display Manager");
display = new DisplayManagerService(context, wmHandler, uiHandler);
ServiceManager.addService(Context.DISPLAY_SERVICE, display, true);
Slog.i(TAG, "Telephony Registry");
telephonyRegistry = new TelephonyRegistry(context);
ServiceManager.addService("telephony.registry", telephonyRegistry);
Slog.i(TAG, "Scheduling Policy");
ServiceManager.addService(Context.SCHEDULING_POLICY_SERVICE,
new SchedulingPolicyService());
AttributeCache.init(context);
if (!display.waitForDefaultDisplay()) {
reportWtf("Timeout waiting for default display to be initialized.",
new Throwable());
}
Slog.i(TAG, "Package Manager");
// Only run "core" apps if we're encrypting the device.
String cryptState = SystemProperties.get("vold.decrypt");
if (ENCRYPTING_STATE.equals(cryptState)) {
Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
onlyCore = true;
} else if (ENCRYPTED_STATE.equals(cryptState)) {
Slog.w(TAG, "Device encrypted - only parsing core apps");
onlyCore = true;
}
pm = PackageManagerService.main(context, installer,
factoryTest != SystemServer.FACTORY_TEST_OFF,
onlyCore);
boolean firstBoot = false;
try {
firstBoot = pm.isFirstBoot();
} catch (RemoteException e) {
}
ActivityManagerService.setSystemProcess();
增加了DisplayManagerService,TelephonyRegistry,SchedulingPolicyService,PackageManagerService,之后又有跟ActivityManagerService有关的setSystemProcess
public static void setSystemProcess() {
try {
ActivityManagerService m = mSelf;
ServiceManager.addService("activity", m, true); //增加activity的service
ServiceManager.addService("meminfo", new MemBinder(m));// 增加meminfo的service
ServiceManager.addService("gfxinfo", new GraphicsBinder(m)); // 增加gfxinfo的service
ServiceManager.addService("dbinfo", new DbBinder(m));// 增加dbinfo的service
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(m)); // 增加cpuinfo的service
}
ServiceManager.addService("permission", new PermissionController(m)); // 增加检查permission的service
ApplicationInfo info =
mSelf.mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS);
mSystemThread.installSystemApplicationInfo(info); // 通过调用mSystemThread.installSystemApplicationInfo函数来把应用程序框架层下面的android包加载进来
synchronized (mSelf) {
ProcessRecord app = mSelf.newProcessRecordLocked(
mSystemThread.getApplicationThread(), info,
info.processName, false);
app.persistent = true;
app.pid = MY_PID;
app.maxAdj = ProcessList.SYSTEM_ADJ;
mSelf.mProcessNames.put(app.processName, app.uid, app);
synchronized (mSelf.mPidsSelfLocked) {
mSelf.mPidsSelfLocked.put(app.pid, app);
}
mSelf.updateLruProcessLocked(app, true);
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
}
可以看出android包信息加载了后,刷新了一下进程信息
我们回到systemserver
Slog.i(TAG, "Entropy Mixer");
ServiceManager.addService("entropy", new EntropyMixer(context));
Slog.i(TAG, "User Service");
ServiceManager.addService(Context.USER_SERVICE,
UserManagerService.getInstance());
mContentResolver = context.getContentResolver();
// The AccountManager must come before the ContentService
try {
Slog.i(TAG, "Account Manager");
accountManager = new AccountManagerService(context);
ServiceManager.addService(Context.ACCOUNT_SERVICE, accountManager);
} catch (Throwable e) {
Slog.e(TAG, "Failure starting Account Manager", e);
}
Slog.i(TAG, "Content Manager");
contentService = ContentService.main(context,
factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
Slog.i(TAG, "System Content Providers");
ActivityManagerService.installSystemProviders();
加入Entropy Mixer,User Service,Account Manager,Content Manager后调用了installSystemProviders
public static final void installSystemProviders() {
List<ProviderInfo> providers;
synchronized (mSelf) {
ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID); // 得到名字为system的进程
providers = mSelf.generateApplicationProvidersLocked(app); // 得到所有与此进程相关的Providers
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); // 通知客户端(ActivityThread)初始化providers
}
mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
mSelf.mUsageStatsService.monitorPackages();
}
// 初始化providers
private void installContentProviders(
Context context, List<ProviderInfo> providers) {
final ArrayList<IActivityManager.ContentProviderHolder> results =
new ArrayList<IActivityManager.ContentProviderHolder>();
for (ProviderInfo cpi : providers) {
if (DEBUG_PROVIDER) {
StringBuilder buf = new StringBuilder(128);
buf.append("Pub ");
buf.append(cpi.authority);
buf.append(": ");
buf.append(cpi.name);
Log.i(TAG, buf.toString());
}
IActivityManager.ContentProviderHolder cph = installProvider(context, null, cpi,
false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
if (cph != null) {
cph.noReleaseNeeded = true;
results.add(cph);
}
}
try {
ActivityManagerNative.getDefault().publishContentProviders(
getApplicationThread(), results);
} catch (RemoteException ex) {
}
}
初始化system provider后,
ActivityManagerService.self().setWindowManager(wm);
设置Windowmanager到activityManagerServices里面
最后设置了安全模式,还有开启其他service systemready
还有com.android.systemui.SystemUIService
当然,还有最重要开启launcher的流程
ActivityManagerService.self().systemReady(new Runnable() {
public void run() {
Slog.i(TAG, "Making services ready");
try {
ActivityManagerService.self().startObservingNativeCrashes(); // 开始监视native是否crash
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
.....
}
}
而真正比较核心的是systemReady函数
public void systemReady(final Runnable goingCallback) {
synchronized(this) {
if (mSystemReady) { // 为false 不走这条路线
if (goingCallback != null) goingCallback.run();
return;
}
// Check to see if there are any update receivers to run.
if (!mDidUpdate) { // 之前没初始化过,走这条路线
if (mWaitingUpdate) { // false
return;
}
Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
List<ResolveInfo> ris = null;
try {
// 从androidmanifest.xml获取有注册ACTION_PRE_BOOT_COMPLETED的
ris = AppGlobals.getPackageManager().queryIntentReceivers(
intent, null, 0, 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) { // 不是systemimage的则删除掉
ris.remove(i);
}
}
intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE); // 增加FLAG_RECEIVER_BOOT_UPGRADE
// data/system/called_pre_boots.dat 读取出之前完成的recevier
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--;
}
}
final int[] users = getUsersLocked();
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);
for (int j=0; j<users.length; j++) {
IIntentReceiver finisher = null;
if (i == ris.size()-1 && j == users.length-1) {
finisher = new IIntentReceiver.Stub() {
public void performReceive(Intent intent, int resultCode,
String data, Bundle extras, boolean ordered,
boolean sticky, int sendingUser) {
// 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()
+ " for user " + users[j]);
// 发送广播
broadcastIntentLocked(null, null, intent, null, finisher,
0, null, null, null, AppOpsManager.OP_NONE,
true, false, MY_PID, Process.SYSTEM_UID,
users[j]);
if (finisher != null) {
mWaitingUpdate = true;
}
}
}
}
if (mWaitingUpdate) { // false
return;
}
mDidUpdate = true; // 被设置为true
}
mAppOpsService.systemReady(); // appOps 准备
mSystemReady = true; // 再次设置为true
if (!mStartRunning) { // 为true
return;
}
}
ArrayList<ProcessRecord> procsToKill = null;
synchronized(mPidsSelfLocked) {
// mPidsSelfLocked 为 0
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) {
// procsToKill 为null
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; // 把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);
}
}
}
// 获取setting的配置 读取content://settings/global 里面debug,finishactivity等值
retrieveSettings();
// 其他service systemready
if (goingCallback != null) goingCallback.run();
synchronized (this) {
// 不是测试模式,但是packagemanagerservice还没有
if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
try {
// 读取固化的app
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, false);
}
}
}
} catch (RemoteException ex) {
// pm is in same process, this will never happen.
}
}
// Start up initial activity.
mBooting = true; // 设置booting完成
//
try {
if (AppGlobals.getPackageManager().hasSystemUidErrors()) { // 是否有system uid error
Message msg = Message.obtain();
msg.what = SHOW_UID_ERROR_MSG;
mHandler.sendMessage(msg);
}
} catch (RemoteException e) {
}
long ident = Binder.clearCallingIdentity();
try {
Intent intent = new Intent(Intent.ACTION_USER_STARTED);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
| Intent.FLAG_RECEIVER_FOREGROUND);
intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
// 发送广播
broadcastIntentLocked(null, null, intent,
null, null, 0, null, null, null, AppOpsManager.OP_NONE,
false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
intent = new Intent(Intent.ACTION_USER_STARTING);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
// 发送广播
broadcastIntentLocked(null, null, intent,
null, new IIntentReceiver.Stub() {
@Override
public void performReceive(Intent intent, int resultCode, String data,
Bundle extras, boolean ordered, boolean sticky, int sendingUser)
throws RemoteException {
}
}, 0, null, null,
android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
} finally {
Binder.restoreCallingIdentity(ident);
}
// 开启top activity
mMainStack.resumeTopActivityLocked(null);
sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
}
}
里面最主要的是resumeTopActivityLocked函数
final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
// Find the first activity that is not finishing.
ActivityRecord next = topRunningActivityLocked(null); // 在history activityrecord里面查找未结束的activity
// Remember how we'll process this pause/resume situation, and ensure
// that the state is reset however we wind up proceeding.
final boolean userLeaving = mUserLeaving;
mUserLeaving = false;
if (next == null) { // 因为第一次,所有为null,所以跑这一步
// There are no more activities! Let's just start up the
// Launcher...
if (mMainStack) {
ActivityOptions.abort(options);
return mService.startHomeActivityLocked(mCurrentUser); // 在这一步开启了Launcher
}
}
。。。。。。
return true;
}
我们可以看到此时这个函数主要是开启launcher
我们看怎么开启launcher的
boolean startHomeActivityLocked(int userId) {
if (mHeadless) { // 是否没有head,不走
// Added because none of the other calls to ensureBootCompleted seem to fire
// when running headless.
ensureBootCompleted();
return false;
}
// 不是测试模式,不走
if (mFactoryTest == SystemServer.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;
}
// 此时mTopAction为main,mTopComponent为null mTopData 为null
Intent intent = new Intent(
mTopAction,
mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
// 再增加CATEGORY_HOME
intent.addCategory(Intent.CATEGORY_HOME);
}
ActivityInfo aInfo =
resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
//
if (aInfo != null) { // 得到launcher
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);
if (app == null || app.instrumentationClass == null) {
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
mMainStack.startActivityLocked(null, intent, null, aInfo,
null, null, 0, 0, 0, null, 0, null, false, null); // 开启launcher
}
}
return true;
}
private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
ActivityInfo ai = null;
ComponentName comp = intent.getComponent();
try {
if (comp != null) {
ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
} else {
ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
intent,
intent.resolveTypeIfNeeded(mContext.getContentResolver()),
flags, userId); // 获取出之前intent带的 resolveInfo ,在里面选择了最合适的resolveInfo回来
if (info != null) {
ai = info.activityInfo;
}
}
} catch (RemoteException e) {
// ignore
}
return ai;
}
最后用
mMainStack.startActivityLocked(null, intent, null, aInfo,
null, null, 0, 0, 0, null, 0, null, false, null);
开启了launcher
一个activity启动过程