編輯:關於 Android 程式設計
SystemServer 由 zygote fork 出來,關於 zygote 如何完成這一步,留待專門討論 zygote 時再說。本文直接從 SystemServer 的 main() 入手,把啟動過程拆開來看。
/*** SystemServer.java ***/
public static void main(String[] args) {
new SystemServer().run();
}
public SystemServer() {
mFactoryTestMode = FactoryTest.getMode();
}
建構子做的事很少,只是確認一下目前是否處於工廠測試模式。物件建好之後,隨即進入 run()。
完整的 run() 很長,裡頭穿插了大量環境初始化:校正早於 1970 年的系統時間、套用語言與區域設定、記錄 persist.sys.dalvik.vm.lib.2、啟動 SamplingProfiler、放寬 VM 記憶體成長上限、設定堆目標使用率、確保 Fingerprint 屬性、把當前程序與執行緒拉到前台優先級、載入 libandroid_servers 等等。
把這些雜項拿掉之後,主幹其實只有三步:
/*** SystemServer.java ***/
private void run() {
Looper.prepareMainLooper();
createSystemContext(); // 1. 初始化系統上下文
mSystemServiceManager = new SystemServiceManager(mSystemContext); // 2. 建立服務管理
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
try {
startBootstrapServices(); // 引導服務
startCoreServices(); // 核心服務
startOtherServices(); // 其餘服務
} catch (Throwable ex) {
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
一句話概括:準備系統上下文 → 建立 SystemServiceManager → 分批啟動所有系統服務 → 進入 Looper 訊息迴圈。
/*** SystemServer.java ***/
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}
三步:建立 ActivityThread、取出系統上下文、設定主題。
/*** ActivityThread.java ***/
public static ActivityThread systemMain() {
if (!ActivityManager.isHighEndGfx()) HardwareRenderer.disable(true);
else HardwareRenderer.enableForegroundTrimming();
ActivityThread thread = new ActivityThread();
thread.attach(true);
return thread;
}
private void attach(boolean system) {
sCurrentActivityThread = this;
mSystemThread = system;
if (system) {
// 讓 system_process 在 DDMS 中有正確名字,否則顯示為 "?"
android.ddm.DdmHandleAppName.setAppName("system_process", UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException("Unable to instantiate Application():" + e.toString(), e);
}
}
DropBox.setReporter(new DropBoxReporter());
ViewRootImpl.addConfigCallback(/* Configuration 變更回呼 */);
}
attach() 主要做三件事:取得並保存系統上下文、由應用上下文建立 Application 並呼叫其 onCreate()、註冊 ComponentCallbacks2 回呼到 ViewRootImpl。
/*** ContextImpl.java ***/
static ContextImpl createSystemContext(ActivityThread mainThread) {
LoadedApk packageInfo = new LoadedApk(mainThread);
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null,
false, null, null, Display.INVALID_DISPLAY);
context.mResources.updateConfiguration(
context.mResourcesManager.getConfiguration(),
context.mResourcesManager.getDisplayMetricsLocked());
return context;
}
static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
return new ContextImpl(null, mainThread, packageInfo, null, null,
false, null, null, Display.INVALID_DISPLAY);
}
兩者構造參數一致,差別在於系統上下文會額外刷新一次 Resources 配置。系統上下文被存進 ActivityThread 的成員變數 mSystemContext,而應用上下文只是區域變數,用完即丟。
/*** LoadedApk.java ***/
public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
if (mApplication != null) return mApplication;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || appClass == null) appClass = "android.app.Application";
Application app = mActivityThread.mInstrumentation.newApplication(
getClassLoader(), appClass, appContext);
appContext.setOuterContext(app);
mActivityThread.mAllApplications.add(app);
mApplication = app;
return app;
}
這一步的資料流是這樣的:系統上下文裡 new 了一個 LoadedApk,並把 ActivityThread 傳進去;後續的 Application 正是由這個 LoadedApk 透過 ActivityThread 的 Instrumentation 建立,建好後登記到 ActivityThread 的應用清單中。
/*** SystemServer.java ***/ mSystemServiceManager = new SystemServiceManager(mSystemContext); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
這一段很單純:new 一個 SystemServiceManager,註冊進本地服務清單。本地服務清單以「類」為鍵,同一類型最多只有一個實例。
/*** SystemServiceManager.java ***/
private final ArrayList<SystemService> mServices = new ArrayList<>();
private int mCurrentPhase = -1;
public <T extends SystemService> T startService(Class<T> serviceClass) {
final T service = serviceClass.getConstructor(Context.class).newInstance(mContext);
mServices.add(service);
service.onStart();
return service;
}
public void startBootPhase(final int phase) {
if (phase <= mCurrentPhase)
throw new IllegalArgumentException("Next phase must be larger than previous");
mCurrentPhase = phase;
for (int i = 0; i < mServices.size(); i++) {
mServices.get(i).onBootPhase(mCurrentPhase);
}
}
值得注意兩點:服務類必須繼承 SystemService 且具備單一 Context 參數的公開建構子(因為走反射建立);開機階段必須單調遞增,每推進一個階段,就遍歷呼叫所有服務的 onBootPhase()。
/*** SystemService.java ***/
public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100;
public static final int PHASE_LOCK_SETTINGS_READY = 480;
public static final int PHASE_SYSTEM_SERVICES_READY = 500;
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;
public static final int PHASE_BOOT_COMPLETED = 1000;
public SystemService(Context context) { mContext = context; }
public abstract void onStart();
public void onBootPhase(int phase) {}
這裡要區分兩種「服務」:系統服務由 SystemServiceManager 管理,而一般 App 服務由 ServiceManager 透過 Binder 機制管理,兩者不是同一套體系。
第一批是彼此高度依賴、必須優先起來的服務:
/*** SystemServer.java ***/
private void startBootstrapServices() {
Installer installer = mSystemServiceManager.startService(Installer.class);
mActivityManagerService = mSystemServiceManager
.startService(ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
mActivityManagerService.initPowerManagement();
mSystemServiceManager.startService(LightsService.class);
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
// 等待默認顯示就緒,最多阻塞 10 秒
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
String cryptState = SystemProperties.get("vold.decrypt");
if (ENCRYPTING_STATE.equals(cryptState) || ENCRYPTED_STATE.equals(cryptState)) mOnlyCore = true;
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());
AttributeCache.init(mSystemContext);
mActivityManagerService.setSystemProcess();
startSensorService();
}
順序不是隨意的:Installer 要先等 installd 就緒;DisplayManagerService 必須在 PackageManager 之前,因為後者需要默認顯示;PackageManagerService 起來後才有 UserManagerService 與 AttributeCache。
/*** SystemServer.java ***/
private void startCoreServices() {
mSystemServiceManager.startService(BatteryService.class); // 依賴 LightService
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();
mSystemServiceManager.startService(WebViewUpdateService.class);
}
這個函式很長,但邏輯單純,基本上就是依序把剩下的服務一個個拉起來。部分服務會依工廠模式或系統屬性決定是否啟動,這裡只列主線:
通訊與連線類:TelecomLoaderService、TelephonyRegistry、BluetoothService、EthernetService、ConnectivityService、NetworkManagementService、NetworkStatsService、NetworkPolicyService、NetworkScoreService、WifiService、WifiP2pService、WifiScanningService、RttService、NsdService、UsbService、SerialService、MidiService。
系統能力類:SchedulingPolicyService、EntropyMixer、CameraService、AccountManagerService、ContentService、VibratorService、ConsumerIrService、AlarmManagerService、WindowManagerService、InputManagerService、InputMethodManagerService、AccessibilityManagerService、MountService、UiModeManagerService、LockSettingsService、PersistentDataBlockService、DeviceIdleController、DevicePolicyManagerService、StatusBarManagerService、NotificationManagerService、ClipboardService、LocationManagerService、CountryDetectorService、SearchManagerService、DropBoxManagerService、WallpaperManagerService、AudioService、JobSchedulerService、BackupManagerService、AppWidgetService、VoiceInteractionManagerService、PrintManagerService、MediaSessionService、MediaRouterService、FingerprintService、TrustManagerService、LauncherAppsService、MediaProjectionManagerService、DreamManagerService 等。
這些服務起來之後,才進入「通知階段」:先推進到 PHASE_LOCK_SETTINGS_READY 與 PHASE_SYSTEM_SERVICES_READY,然後依序呼叫 wm.systemReady()、powerManager.systemReady()、packageManager.systemReady()、displayManager.systemReady(),最後交給 mActivityManagerService.systemReady() 的 Runnable:
mActivityManagerService.systemReady(new Runnable() {
@Override public void run() {
mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);
mActivityManagerService.startObservingNativeCrashes();
WebViewFactory.prepareWebViewInSystemServer();
startSystemUi(context);
// 各服務的 systemReady / systemRunning
Watchdog.getInstance().start();
mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
wallpaperF.systemRunning();
immF.systemRunning(statusBarF);
// ...
}
});
當 PHASE_THIRD_PARTY_APPS_CAN_START 被觸發、SystemUI 起來、Watchdog 開始運轉,SystemServer 的啟動任務就算完成了,此後它便安靜地待在 Looper.loop() 裡等待訊息。
Android 使用 PopupWindow 實作彈出視窗(可用於提示等)
效果圖如下: PopupWindow 是一個能顯示於當前 Activity 之上的浮動容器。它彈出的位置可以調整:依有無偏移量分為「無偏移」與「有偏移」兩種;依參照對象
Android 開發中常見的資料儲存方式詳解
在 Android 中,資料的儲存大致可分為兩種方式:1、直接以檔案形式儲存在目錄中; 2、以資料庫形式儲存。而「以檔案儲存」又可再細分為兩種:1、產生 .txt 檔;
人在外面也能遙控電腦!用手機遠端控制 PC 的實作教學
出門之後才想起電腦沒關,或者發現重要檔案忘了從電腦裡拷出來——難道真要特地跑回家一趟?其實在外網環境下用手機遙控電腦,沒有你想的那麼複雜。 用 TeamViewer 搭起
Android JNI 與 NDK 開發入門:從 Builder 設定到第一個 so
NDK 讓 Android 開發者能用 C 或 C++ 撰寫原生程式,並打包成 so 動態庫。自 NDK r7 之後,Windows 環境已可直接使用 ndk-build