Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中集結的大量系統管家 Manager 探秘

編輯:關於 Android 程式設計

Android 系統中集結了大量的系統管家 Manager:當你要 kill 一個後台 Process 時會用到 ActivityManager,需要處理聲音相關功能時會用到 AudioManager 等等。而獲取這些管家非常簡單,只需調用當前 context 的 getSystemService 方法即可:

final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

那麼,為什麼任意 context 實例都能獲取 Manager 呢?本文將揭開其中的秘密。

一、Context 與 ContextImpl

Context 描述了 application 的全域資源與資訊,它是一個抽象類,其實作類是 ContextImpl。Android 對 ContextImpl 的原文介紹為:它是 Context API 的通用實作,為 Activity 及其他應用組件提供基礎的 context 對象。也就是說,應用組件其實都繼承於它。

二、getSystemService 的秘密

ContextImpl 中的 getSystemService 從一個 SYSTEM_SERVICE_MAP 中取出對應的 ServiceFetcher:

public Object getSystemService(String name) {

ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);

return fetcher == null ? null : fetcher.getService(this);

}

這裡有兩個關鍵:SYSTEM_SERVICE_MAP 是一個 static 的 HashMap,存儲著公共共用的 ServiceFetcher;而 ServiceFetcher 則是一個封裝類,其中的 getService 方法會先檢查 ctx.mServiceCache 是否已有該服務,若無則呼叫 createService 創建。

三、服務的註冊

在 ContextImpl 中有一段 static 代碼,透過 registerService 註冊了所有系統服務。registerService 本質上就是把創建好的 ServiceFetcher 存進 SYSTEM_SERVICE_MAP 這個 HashMap 中。

四、常見的 Manager 服務

系統中內建的服務不勝枚舉,例如:

PowerManagerService:電源管理,負責待機關閉設備、螢幕背光等。

ActivityManagerService:framework 中最核心的服務,管理任務、進程與四大組件的生命週期。

PackageManagerService:負責軟件包的解包、驗證、安裝與升級。

WindowManagerService:窗口管理,核心為輸入事件的分發。

AlarmManager、NotificationManager、LocationManager、AudioManager、SensorManager 等,分別負責鬧鐘、通知、定位、音頻與感測器等各類系統能力。

透過這套設計,Android 將繁多的系統能力統一封裝為各類 Manager,並以 HashMap 集中管理、按需創建,既保證了結構清晰,也讓開發者能輕鬆獲取所需的系統服務。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved