android 启动-SystemServer-Activity
主要介绍在system server 启动过程中, ActivityManagerService 的启动过程,及其主要的工作
流程
对上图的systemReady 进行细分:
frameworks/base/services/java/com/android/server/SystemServer.java
mActivityManagerService.systemReady
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog)
下面分析code:
frameworks/base/services/java/com/android/server/SystemServer.java
run:
......
startBootstrapServices();----》第一部分
startCoreServices();----》第二部分
startOtherServices();----》第三部分
......
第一部分
frameworks/base/services/java/com/android/server/SystemServer.java
startBootstrapServices()
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();----》创建
//mActivityManagerService 管理器 mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);---->设定app 安装管理器
mActivityManagerService.initPowerManagement();---》初始化power manager
//进入了 startBootPhase 100 阶段 mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);//100
//设定AcitivtiyManagerService process system_server 信息
mActivityManagerService.setSystemProcess();
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
ActivityManagerService.Lifecycle
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context); ---->创建ActivityManagerService
}
@Override
public void onStart() {
mService.start();---》 启动ActivityManagerService
}
public ActivityManagerService getService() {
return mService;
}
}
分析ActivityManagerService 在构造的时候具体做了什么事情
创建了线程:ServiceThread,mUiHandler ,sKillThread ,CpuTracker
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
ActivityManagerService
// handlers to other threads. So take care to be explicit about the looper.
public ActivityManagerService(Context systemContext) {
LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
mInjector = new Injector();
mContext = systemContext;
mFactoryTest = FactoryTest.getMode();
mSystemThread = ActivityThread.currentActivityThread()//---->mSystemThread
mUiContext = mSystemThread.getSystemUiContext();
Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
mPermissionReviewRequired = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_permissionReviewRequired);
//ActivityManagerService thread 创建
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper()); //创建handle thread
mUiHandler = mInjector.getUiHandler(this);
mConstants = new ActivityManagerConstants(this, mHandler);
/* static; one-time init here */
if (sKillHandler == null) {
sKillThread = new ServiceThread(TAG + ":kill", ----> kill thread
THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
sKillThread.start();
sKillHandler = new KillHandler(sKillThread.getLooper());
}
// 前台 static final int BROADCAST_FG_TIMEOUT = 10*1000;
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", BROADCAST_FG_TIMEOUT, false);
//后台 static final int BROADCAST_BG_TIMEOUT = 60*1000;
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", BROADCAST_BG_TIMEOUT, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
mServices = new ActiveServices(this);
mProviderMap = new ProviderMap(this);
mAppErrors = new AppErrors(mUiContext, this);
// TODO: Move creation of battery stats service outside of activity manager service.
File dataDir = Environment.getDataDirectory();
创建/datat/system
File systemDir = new File(dataDir, "system");
systemDir.mkdirs();
mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
mBatteryStatsService.getActiveStatistics().readLocked();
mBatteryStatsService.scheduleWriteToDisk();
mOnBattery = DEBUG_POWER ? true
: mBatteryStatsService.getActiveStatistics().getIsOnBattery();
mBatteryStatsService.getActiveStatistics().setCallback(this);
//创建进程的/data/system/procstats 状态
mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
new IAppOpsCallback.Stub() {
@Override public void opChanged(int op, int uid, String packageName) {
if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
if (mAppOpsService.checkOperation(op, uid, packageName)
!= AppOpsManager.MODE_ALLOWED) {
runInBackgroundDisabled(uid);
}
}
}
});
mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
// 创建用户
mUserController = new UserController(this);
mVrController = new VrController(this);
GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
mUseFifoUiScheduling = true;
}
mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
mTempConfig.setToDefaults();
mTempConfig.setLocales(LocaleList.getDefault());
mConfigurationSeq = mTempConfig.seq = 1;
//监听
mStackSupervisor = createStackSupervisor();
mStackSupervisor.onConfigurationChanged(mTempConfig);
mKeyguardController = mStackSupervisor.mKeyguardController;
mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
mTaskChangeNotificationController =
new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
mActivityStarter = new ActivityStarter(this, mStackSupervisor);
mRecentTasks = new RecentTasks(this, mStackSupervisor);
// 创建CpuTracker
mProcessCpuThread = new Thread("CpuTracker") {
@Override
public void run() {
synchronized (mProcessCpuTracker) {
mProcessCpuInitLatch.countDown();
mProcessCpuTracker.init();
}
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);
}
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
onStart--》 mService.start();
private void start() {
removeAllProcessGroups(); -->移除所有processgroup
mProcessCpuThread.start(); ---->start cpu 监控
mBatteryStatsService.publish(); -----》电池states publish
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
// Wait for the synchronized block started in mProcessCpuThread,
// so that any other acccess to mProcessCpuTracker from main thread
// will be blocked during mProcessCpuTracker initialization.
try {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
mActivityManagerService.setInstaller(installer);
Installer installer = mSystemServiceManager.startService(Installer.class);
frameworks/base/services/core/java/com/android/server/pm/Installer.java
public class Installer extends SystemService { ---->继承SystemService
@Override
public void onStart() {---》启动
connect();
}
private void connect() { ----》bind connect
IBinder binder = ServiceManager.getService("installd");
}
}
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
mActivityManagerService.initPowerManagement();
public void initPowerManagement() {
mStackSupervisor.initPowerManagement();
mBatteryStatsService.initPowerManagement(); --->init power
mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
mVoiceWakeLock.setReferenceCounted(false);
}
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
mActivityManagerService.setSystemProcess();
dumpsys 服务
--》这种指令可以查看服务状态
activity
-->ActivityManagerService:AMS 状态
procstats
-->ProcessStatsService :进程统计
meminfo
-->MemBinder :内存
gfxinfo
-->GraphicsBinder :图像信息
dbinfo
-->DbBinder :数据库
cpuinfo
-->CpuBinder :CPU
permission
-->PermissionController :权限
processinfo
-->ProcessInfoService :进程服务
usagestats
-->UsageStatsService :应用的使用情况
public void setSystemProcess() {
try {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this));-----> add meminfo to service 内存
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));-----> add gfxinfoto service 图形
ServiceManager.addService("dbinfo", new DbBinder(this));-----> add dbinfoto service 数据库
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this));-----> add cpuinfo service 处理器
}
ServiceManager.addService("permission", new PermissionController(this));-----> add permission service 权限
ServiceManager.addService("processinfo", new ProcessInfoService(this));-----> add processinfo service 进程信息
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);------》package name: android
// ---》安装 app 信息, 包名是android, ··framework-res.apk ··
mSystemThread.installSystemApplicationInfo(info,getClass().getClassLoader());
synchronized (this) {
ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0); ---》创建processRecord
app.persistent = true;
app.pid = MY_PID;
app.maxAdj = ProcessList.SYSTEM_ADJ;
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);
}
}
framework/base/core/java/android/app/ActivityThread.java
mSystemThread.installSystemApplicationInfo---->
public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
synchronized (this) {
getSystemContext().installSystemApplicationInfo(info, classLoader);
getSystemUiContext().installSystemApplicationInfo(info, classLoader);
// give ourselves a default profiler,默认性能统计使用
mProfiler = new Profiler();
}
}
framework/base/core/java/android/app/ActivityThread.java
getSystemContext().installSystemApplicationInfo-->
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
mSystemContext = ContextImpl.createSystemContext(this);---->ContextImpl
}
return mSystemContext;
}
}
framework/base/core/java/android/app/ContextImpl.javaj
ContextImpl-->installSystemApplicationInfo
class ContextImpl extends Context {
private final static String TAG = "ContextImpl";
private final static boolean DEBUG = false;
.....
void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
//安装了systemapp 包名是android,
mPackageInfo.installSystemApplicationInfo(info, classLoader);
}
......
最后调用了loadedapk
framework/base/core/java/android/app/LoadedApk.java
mPackageInfo.installSystemApplicationInfo--》
void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
assert info.packageName.equals("android");
mApplicationInfo = info;
mClassLoader = classLoader;
}
第二部分
frameworks/base/services/java/com/android/server/SystemServer.java
startCoreServices()
// user0 是第一个用户,这里设定用户状态manager
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
第三部分
frameworks/base/services/java/com/android/server/SystemServer.java
startOtherServices()
mActivityManagerService.installSystemProviders(); // 安装providers
mActivityManagerService.setWindowManager(wm); //设定wm
mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY); //480
mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);//500
mActivityManagerService.systemReady { ----> // 使用了callback 分阶段运行
}
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
mActivityManagerService.installSystemProviders()
public final void installSystemProviders() {
List<ProviderInfo> providers;
synchronized (this) {
//获取system_server
ProcessRecord app = mProcessNames.get("system", SYSTEM_UID);
providers = 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);---->移除非系统的providers
}
}
}
}
if (providers != null) {
mSystemThread.installSystemProviders(providers);----> 安装系统providers
}
mConstants.start(mContext.getContentResolver());
//创建setting observer
mCoreSettingsObserver = new CoreSettingsObserver(this);
mFontScaleSettingObserver = new FontScaleSettingObserver();
// Now that the settings provider is published we can consider sending
// in a rescue party. -->考虑了rescue 情况 provider publish
RescueParty.onSettingsProviderPublished(mContext);
//mUsageStatsService.monitorPackages();
}
下面分析callback 方式的mActivityManagerService.systemReady,有第二张图已经说明了,从system_server 到ActivityManagerSerivce 交互过程
systemReady 原型
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog)
goingCallback 采用了匿名方式,在systemReady 函数体中,中间调用了callback,mActivityManagerService.systemReady(callback)
下面就是callback 函数体
frameworks/base/services/java/com/android/server/SystemServer.java
mActivityManagerService.systemReady(() -> {
Slog.i(TAG, "Making services ready");
traceBeginAndSlog("StartActivityManagerReadyPhase");
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);//500
traceEnd();
traceBeginAndSlog("StartObservingNativeCrashes");
try {
mActivityManagerService.startObservingNativeCrashes();// 启动监听crash
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
traceEnd();
// No dependency on Webview preparation in system server. But this should
// be completed before allowring 3rd party
final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
Future<?> webviewPrep = null;
if (!mOnlyCore) {
webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
Slog.i(TAG, WEBVIEW_PREPARATION);
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(WEBVIEW_PREPARATION);
ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
mZygotePreload = null;
mWebViewUpdateService.prepareWebViewInSystemServer();
traceLog.traceEnd();
}, WEBVIEW_PREPARATION);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
traceBeginAndSlog("StartCarServiceHelperService");
mSystemServiceManager.startService(CarServiceHelperService.class);//启动CarServiceHelperService
traceEnd();
}
traceBeginAndSlog("StartSystemUI");
try {
startSystemUi(context, windowManagerF);//启动UI
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
traceEnd();
traceBeginAndSlog("MakeNetworkScoreReady");
try {
if (networkScoreF != null) networkScoreF.systemReady();// 网络score ready
} catch (Throwable e) {
reportWtf("making Network Score Service ready", e);
}
traceEnd();
traceBeginAndSlog("MakeNetworkManagementServiceReady");
try {
if (networkManagementF != null) networkManagementF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Managment Service ready", e);
}
CountDownLatch networkPolicyInitReadySignal = null;
if (networkPolicyF != null) {
networkPolicyInitReadySignal = networkPolicyF
.networkScoreAndNetworkManagementServiceReady();
}
traceEnd();
///---->MakeNetworkStatsServiceReady traceBeginAndSlog("MakeNetworkStatsServiceReady");
try {
if (networkStatsF != null) networkStatsF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Stats Service ready", e);
}
traceEnd();
traceBeginAndSlog("MakeConnectivityServiceReady");
try {
if (connectivityF != null) connectivityF.systemReady();
} catch (Throwable e) {
reportWtf("making Connectivity Service ready", e);
}
traceEnd();
traceBeginAndSlog("MakeNetworkPolicyServiceReady");
try {
if (networkPolicyF != null) {
networkPolicyF.systemReady(networkPolicyInitReadySignal);
}
} catch (Throwable e) {
reportWtf("making Network Policy Service ready", e);
}
traceEnd();
traceBeginAndSlog("StartWatchdog");
Watchdog.getInstance().start(); //启动watchdog
traceEnd();
// Wait for all packages to be prepared
mPackageManagerService.waitForAppDataPrepared();
// It is now okay to let the various system services start their
// third party code...
traceBeginAndSlog("PhaseThirdPartyAppsCanStart");
// confirm webview completion before starting 3rd party
if (webviewPrep != null) {
ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
}
mSystemServiceManager.startBootPhase(
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);//600
traceEnd();
traceBeginAndSlog("NrealControllerAutoConnectServiceRedy");
try {
if (mNrealControllerAutoConnectService != null)
mNrealControllerAutoConnectService.systemReady(safeMode, mOnlyCore);
} catch (Throwable e) {
reportWtf("NrealControllerAutoConnectService running", e);
}
traceEnd();
traceBeginAndSlog("MakeLocationServiceReady");
try {
if (locationF != null) locationF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying Location Service running", e);
}
traceEnd();
traceBeginAndSlog("MakeCountryDetectionServiceReady");
try {
if (countryDetectorF != null) countryDetectorF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying CountryDetectorService running", e);
}
traceEnd();
traceBeginAndSlog("MakeNetworkTimeUpdateReady");
try {
if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying NetworkTimeService running", e);
}
traceEnd();
traceBeginAndSlog("MakeCommonTimeManagementServiceReady");
try {
if (commonTimeMgmtServiceF != null) {
commonTimeMgmtServiceF.systemRunning();
}
} catch (Throwable e) {
reportWtf("Notifying CommonTimeManagementService running", e);
}
traceEnd();
traceBeginAndSlog("MakeInputManagerServiceReady");
try {
// TODO(BT) Pass parameter to input manager
if (inputManagerF != null) inputManagerF.systemRunning();/// input manager ready
} catch (Throwable e) {
reportWtf("Notifying InputManagerService running", e);
}
traceEnd();
traceBeginAndSlog("MakeTelephonyRegistryReady");
try {
if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying TelephonyRegistry running", e);
}
traceEnd();
traceBeginAndSlog("MakeMediaRouterServiceReady");
try {
if (mediaRouterF != null) mediaRouterF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying MediaRouterService running", e);
}
traceEnd();
traceBeginAndSlog("MakeMmsServiceReady");
try {
if (mmsServiceF != null) mmsServiceF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying MmsService running", e);
}
traceEnd();
traceBeginAndSlog("MakeNetworkScoreServiceReady");
try {
if (networkScoreF != null) networkScoreF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying NetworkScoreService running", e);
}
traceEnd();
traceBeginAndSlog("IncidentDaemonReady");
try {
// TODO: Switch from checkService to getService once it's always
// in the build and should reliably be there.
final IIncidentManager incident = IIncidentManager.Stub.asInterface(
ServiceManager.checkService("incident"));
if (incident != null) incident.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying incident daemon running", e);
}
traceEnd();
}, BOOT_TIMINGS_TRACE_LOG);
下面就是systemReady(callback)函数体
frameworks/base/services/java/com/android/server/SystemServer.java
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
traceLog.traceBegin("PhaseActivityManagerReady");
synchronized(this) {
if (mSystemReady) {
// If we're done calling all the receivers, run the next "boot phase" passed in
// by the SystemServer
if (goingCallback != null) {
goingCallback.run();
}
return;
}
mLocalDeviceIdleController
= LocalServices.getService(DeviceIdleController.LocalService.class);
mAssistUtils = new AssistUtils(mContext);
mVrController.onSystemReady();
// Make sure we have the current profile info, since it is needed for security checks.
mUserController.onSystemReady();
mRecentTasks.onSystemReadyLocked();
mAppOpsService.systemReady();
mSystemReady = true;
}
try {
sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
.getSerial();
} catch (RemoteException e) {}
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);// kill proc 杀死没有boot 运行的进程
}
}
}
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; //process 准备好了
}
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 == FactoryTest.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_UI_MSG;
msg.getData().putCharSequence("msg", errorMsg);
mUiHandler.sendMessage(msg);
}
}
}
retrieveSettings();
final int currentUserId;
synchronized (this) {
currentUserId = mUserController.getCurrentUserIdLocked();
readGrantedUriPermissionsLocked();
}
if (goingCallback != null) goingCallback.run();----》 启动callback 调用
traceLog.traceBegin("ActivityManagerStartApps");
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
Integer.toString(currentUserId), currentUserId);
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
Integer.toString(currentUserId), currentUserId);
mSystemServiceManager.startUser(currentUserId);
synchronized (this) {
// Only start up encryption-aware persistent apps; once user is
// unlocked we'll come back around and start unaware apps
// 启动系统persisit app startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
// Start up initial activity.
mBooting = true;
// Enable home activity for system user, so that the system can always boot. We don't
// do this when the system user is not setup since the setup wizard should be the one
// to handle home activity in this case.
if (UserManager.isSplitSystemUser() &&
Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
try {
AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
UserHandle.USER_SYSTEM);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
startHomeActivityLocked(currentUserId, "systemReady");--------> 启动桌面, 在这里发送PHASE_BOOT_COMPLETED=1000
try {
if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
+ " data partition or your device will be unstable.");
mUiHandler.obtainMessage(SHOW_UID_ERROR_UI_MSG).sendToTarget();
}
} catch (RemoteException e) {
}
if (!Build.isBuildConsistent()) {
Slog.e(TAG, "Build fingerprint is not consistent, warning user");
mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_UI_MSG).sendToTarget();
}
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, currentUserId);
broadcastIntentLocked(null, null, intent,
null, null, 0, null, null, null, AppOpsManager.OP_NONE,
null, false, false, MY_PID, SYSTEM_UID,
currentUserId);
intent = new Intent(Intent.ACTION_USER_STARTING);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
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,
new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
} catch (Throwable t) {
Slog.wtf(TAG, "Failed sending first user broadcasts", t);
} finally {
Binder.restoreCallingIdentity(ident);
}
mStackSupervisor.resumeFocusedStackTopActivityLocked();
mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
traceLog.traceEnd(); // ActivityManagerStartApps
traceLog.traceEnd(); // PhaseActivityManagerReady
}
}
下篇文章讲到,UI 启动,中发送PHASE_BOOT_COMPLETED
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
PHASE_BOOT_COMPLETED=1000发送过程
startHomeActivityLocked
startHomeActivityLocked
moveHomeStackTaskToTop--》
moveFocusableActivityStackToFrontLocked-----》
moveToFront---》
setFocusStackUnchecked---》
checkFinishBootingLocked--》
mService.postFinishBooting-------->FINISH_BOOTING_MSG
finishBooting()---->
// Let system services know.
mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED); -->之前桌面已经加载
#public static final int PHASE_BOOT_COMPLETED = 1000;
final void finishBooting() {
.......
}