Android SystemService介紹一

SystemService 干嘛的。

Android SystemService 是framework的一些對應(yīng)功能的服務(wù)供其他模塊和app 來調(diào)用主穗。例如 BatteryService(用來獲取電池屬性泻拦,充電狀態(tài),百分比等)忽媒,PowerManagerService(休眠争拐,wakeup 等),TvInputManagerService(創(chuàng)建session晦雨,releaseSession 等)等都是常用的系統(tǒng)服務(wù)架曹,基本都是一個模塊相關(guān)的功能在一個服務(wù)里面。

SystemService 的使用

使用比較簡單闹瞧,主要是通過 context.getSystemService(@NonNull Class<T> serviceClass)或者Object getSystemService(@ServiceName @NonNull String name) 獲取一個manager 對象绑雄,去調(diào)用SystemService 里面的方法。
例如: 使用PowerManagerService 去喚醒屏幕奥邮。

  public static void wakeScreenIfScreenOff(Context context){
        PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        boolean interactive = powerManager.isInteractive();
        Log.d(TAG,"checkScreen interactive :"+interactive);
        if (!interactive) {
            powerManager.wakeUp(SystemClock.uptimeMillis(),PowerManager.WAKE_REASON_APPLICATION,"android.policy:KEY");
        }
    }

SystemService 往往對應(yīng)的有Manager 万牺,app 通過獲取Manager 調(diào)用Manager 里面的方法去調(diào)用到Service里面。

SystemService 和對應(yīng)的Manager

Manager 和SystemService 通過AIDL 來進(jìn)行通信洽腺。關(guān)系是
app --》 Manager --》 SystemService脚粟。
以DeviceStateManager 和 DeviceStateManagerService 為例。
IDeviceStateManager.aidl 代碼如下

interface IDeviceStateManager {
    DeviceStateInfo getDeviceStateInfo();
    void requestState(IBinder token, int state, int flags);
    void cancelRequest(IBinder token);
}

DeviceStateManagerGlobal.java 部分代碼如下

public final class DeviceStateManagerGlobal {
    private static DeviceStateManagerGlobal sInstance;
    static DeviceStateManagerGlobal getInstance() {
        synchronized (DeviceStateManagerGlobal.class) {
            if (sInstance == null) {
                IBinder b = ServiceManager.getService(Context.DEVICE_STATE_SERVICE);
                if (b != null) {
                    sInstance = new DeviceStateManagerGlobal(IDeviceStateManager
                            .Stub.asInterface(b));
                }
            }
            return sInstance;
        }
    }
}

DeviceStateManagerService 的代碼 BinderService 繼承AIDL 類型已脓,DeviceStateManagerGlobal 里賣初始化的類型珊楼。

public final class DeviceStateManagerService extends SystemService {
···
    DeviceStateManagerService(@NonNull Context context, @NonNull DeviceStatePolicy policy) {
        super(context);
     ···
        mBinderService = new BinderService();
    }

    @Override
    public void onStart() {
        publishBinderService(Context.DEVICE_STATE_SERVICE, mBinderService); 
// 調(diào)用 到  ServiceManager.addService(name, service, allowIsolated, dumpPriority);
    }

 
    private final class BinderService extends IDeviceStateManager.Stub {
        @Override // Binder call
        public DeviceStateInfo getDeviceStateInfo() {
            ···
        }

        @Override // Binder call
        public void registerCallback(IDeviceStateManagerCallback callback) {
          ···
        }

        @Override // Binder call
        public void requestState(IBinder token, int state, int flags) {
      ···
        }

        @Override // Binder call
        public void cancelRequest(IBinder token) {
         ···
        }

        @Override // Binder call
        public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
                String[] args, ShellCallback callback, ResultReceiver result) {
           ···
        }

        @Override // Binder call
        public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
          ···
        }
    }
}

DeviceStateManager 調(diào)用 的代碼

public final class DeviceStateManager {
   ···
    public DeviceStateManager() {
        DeviceStateManagerGlobal global = DeviceStateManagerGlobal.getInstance();
        if (global == null) {
            throw new IllegalStateException(
                    "Failed to get instance of global device state manager.");
        }
        mGlobal = global;
    }


    @NonNull
    public int[] getSupportedStates() {
        return mGlobal.getSupportedStates();
    }

@RequiresPermission(android.Manifest.permission.CONTROL_DEVICE_STATE)
    public void requestState(@NonNull DeviceStateRequest request,
            @Nullable @CallbackExecutor Executor executor,
            @Nullable DeviceStateRequest.Callback callback) {
        mGlobal.requestState(request, callback, executor);
    }
    @RequiresPermission(android.Manifest.permission.CONTROL_DEVICE_STATE)
    public void cancelRequest(@NonNull DeviceStateRequest request) {
        mGlobal.cancelRequest(request);
    }

    public void registerCallback(@NonNull @CallbackExecutor Executor executor,
            @NonNull DeviceStateCallback callback) {
        mGlobal.registerDeviceStateCallback(callback, executor);
    }
    public void unregisterCallback(@NonNull DeviceStateCallback callback) {
        mGlobal.unregisterDeviceStateCallback(callback);
    }
···
}

上面可以看出 DeviceStateManager 通過 DeviceStateManagerGlobal 調(diào)用到 IBinder b 里面通殃。
IBinder b = ServiceManager.getService(Context.DEVICE_STATE_SERVICE);
publishBinderService 與 ServiceManager.getService 相對應(yīng)度液。這樣DeviceStateManager 通過DeviceStateManagerGlobal 獲取到DeviceStateManager Service對應(yīng)的IBinder,同歸aidl 調(diào)用到DeviceStateManagerService 里面画舌。DeviceStateManager 暴露給app 來調(diào)用堕担。

SystemService 和對應(yīng)的Manager 的初始化

SystemServer 是由 Zygote ( Zygote 是啥干啥的,怎么啟動 )分裂出來的第一個java進(jìn)程曲聂,SystemService 和對應(yīng)的Manager都是在 SystemServer 初始化

SystemServer {
    public static void main(String[] args) {
        new SystemServer().run();
    }
···
    private void run() {
···
         SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
···
         mSystemServiceManager = new SystemServiceManager(mSystemContext);
        startBootstrapServices(t); // 啟動應(yīng)的 SystemServices
           ···
        startCoreServices(t);// 啟動應(yīng)的 SystemServices
          ···
       startOtherServices(t);// 啟動應(yīng)的 SystemServices
    }

private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
      ···
       mSystemServiceManager.startService(SystemConfigService.class);
     mSystemServiceManager.startService(BatteryService.class);
    mSystemServiceManager.startService(UsageStatsService.class);
mSystemServiceManager.startService(CachedDeviceStateService.class);
 mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);

···
}
  

···
}

SystemServiceManager 里面 startService

    public <T extends SystemService> T startService(Class<T> serviceClass) {
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
           ···
            final T service; //反射初始化
  service = constructor.newInstance(mContext);
           ···
            startService(service);
            return service;
    }

    public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        service.onStart();
    }

SystemService 里面 onStart(),主要是把 aidl 的對應(yīng)的binder 對象 存儲起來霹购。例如 DeviceStateManagerService里面

DeviceStateManagerService{
    DeviceStateManagerService(@NonNull Context context, @NonNull DeviceStatePolicy policy) {
        super(context);
        ···
        mBinderService = new BinderService(); 
    }

    @Override
    public void onStart() {
        publishBinderService(Context.DEVICE_STATE_SERVICE, mBinderService);
    }
}
SystemService{
···
    protected final void publishBinderService(String name, IBinder service,
            boolean allowIsolated, int dumpPriority) {
        ServiceManager.addService(name, service, allowIsolated, dumpPriority);
    }

···
}

SystemServer 進(jìn)程初始化的時候 run方法 對SystemService 進(jìn)行了初始化。
publishBinderService調(diào)用到ServiceManager(ServiceManager 是干嘛的朋腋,有啥用齐疙,跟進(jìn)程間通信的關(guān)系)的 addService

ServiceManager{
    public static void addService(String name, IBinder service, boolean allowIsolated,
            int dumpPriority) {
            getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
    }
···
@UnsupportedAppUsage
    private static IServiceManager getIServiceManager() {
        if (sServiceManager != null) {
            return sServiceManager;
        }

        // Find the service manager
        sServiceManager = ServiceManagerNative
                .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
        return sServiceManager;
    }

}

IServiceManager 的實(shí)現(xiàn)都是native層ServiceManager.c++ 目錄再framework/native/cmds/servicemanager/ServiceManager.cpp

···
Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
    *outBinder = tryGetService(name, true);
    // returns ok regardless of result for legacy reasons
    return Status::ok();
}
···
Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
    *outBinder = tryGetService(name, false);
    // returns ok regardless of result for legacy reasons
    return Status::ok();
}
···
Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
    auto ctx = mAccess->getCallingContext();
    // apps cannot add services
    if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
        return Status::fromExceptionCode(Status::EX_SECURITY);
    }

    if (!mAccess->canAdd(ctx, name)) {
        return Status::fromExceptionCode(Status::EX_SECURITY);
    }

    if (binder == nullptr) {
        return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
    }

    if (!isValidServiceName(name)) {
        LOG(ERROR) << "Invalid service name: " << name;
        return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
    }

#ifndef VENDORSERVICEMANAGER
    if (!meetsDeclarationRequirements(binder, name)) {
        // already logged
        return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
    }
#endif  // !VENDORSERVICEMANAGER

    // implicitly unlinked when the binder is removed
    if (binder->remoteBinder() != nullptr &&
        binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
        LOG(ERROR) << "Could not linkToDeath when adding " << name;
        return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
    }

    // Overwrite the old service if it exists
    mNameToService[name] = Service {
        .binder = binder,
        .allowIsolated = allowIsolated,
        .dumpPriority = dumpPriority,
        .debugPid = ctx.debugPid,
    };

    auto it = mNameToRegistrationCallback.find(name);
    if (it != mNameToRegistrationCallback.end()) {
        for (const sp<IServiceCallback>& cb : it->second) {
            mNameToService[name].guaranteeClient = true;
            // permission checked in registerForNotifications
            cb->onRegistration(name, binder);
        }
    }
    return Status::ok();
}

SystemServer run 方法 調(diào)用到SystemServiceRegistry膜楷,他的static 代碼塊就會自動調(diào)用到。
SystemServiceRegistry static 代碼塊里面對各個Manager 進(jìn)行了初始化(或者叫聲明初始化)贞奋。

SystemServiceRegistry {

static{
registerService(Context.USB_SERVICE, UsbManager.class,
                new CachedServiceFetcher<UsbManager>() {
            @Override
            public UsbManager createService(ContextImpl ctx) throws ServiceNotFoundException {
                IBinder b = ServiceManager.getServiceOrThrow(Context.USB_SERVICE);
                return new UsbManager(ctx, IUsbManager.Stub.asInterface(b));
            }});
        registerService(Context.ADB_SERVICE, AdbManager.class,
                new CachedServiceFetcher<AdbManager>() {
                    @Override
                    public AdbManager createService(ContextImpl ctx)
                                throws ServiceNotFoundException {
                        IBinder b = ServiceManager.getServiceOrThrow(Context.ADB_SERVICE);
                        return new AdbManager(ctx, IAdbManager.Stub.asInterface(b));
                    }});
}

    private static final Map<Class<?>, String> SYSTEM_SERVICE_NAMES =
            new ArrayMap<Class<?>, String>();
    private static final Map<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
            new ArrayMap<String, ServiceFetcher<?>>();
       // 把 注冊manager 當(dāng)context 獲取的時候就調(diào)用到Manager
    private static <T> void registerService(String serviceName, Class<T> serviceClass,
            ServiceFetcher<T> serviceFetcher) {
        SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
        SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
    }

    public static Object getSystemService(ContextImpl ctx, String name) {
        ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
        return fetcher != null ? fetcher.getService(ctx) : null;
    }

    public static String getSystemServiceName(Class<?> serviceClass) {
        return SYSTEM_SERVICE_NAMES.get(serviceClass);
    }
···
}

CachedServiceFetcher 有兩個特點(diǎn)赌厅,1 cache 緩存 不重復(fù)創(chuàng)建 2 Fetcher 等到用的時候在創(chuàng)建,類似于懶加載轿塔。
ContextImpl 里面就是通過 SystemServiceRegistry.getSystemService 獲取Manager

ContextImpl {
···
  @Override
    public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }
···
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末特愿,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子勾缭,更是在濱河造成了極大的恐慌揍障,老刑警劉巖,帶你破解...
    沈念sama閱讀 210,978評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件俩由,死亡現(xiàn)場離奇詭異毒嫡,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)幻梯,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,954評論 2 384
  • 文/潘曉璐 我一進(jìn)店門审胚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人礼旅,你說我怎么就攤上這事膳叨。” “怎么了痘系?”我有些...
    開封第一講書人閱讀 156,623評論 0 345
  • 文/不壞的土叔 我叫張陵菲嘴,是天一觀的道長。 經(jīng)常有香客問我汰翠,道長龄坪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,324評論 1 282
  • 正文 為了忘掉前任复唤,我火速辦了婚禮健田,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘佛纫。我一直安慰自己妓局,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,390評論 5 384
  • 文/花漫 我一把揭開白布呈宇。 她就那樣靜靜地躺著好爬,像睡著了一般。 火紅的嫁衣襯著肌膚如雪甥啄。 梳的紋絲不亂的頭發(fā)上存炮,一...
    開封第一講書人閱讀 49,741評論 1 289
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼穆桂。 笑死宫盔,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的享完。 我是一名探鬼主播飘言,決...
    沈念sama閱讀 38,892評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼驼侠!你這毒婦竟也來了姿鸿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,655評論 0 266
  • 序言:老撾萬榮一對情侶失蹤倒源,失蹤者是張志新(化名)和其女友劉穎苛预,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體笋熬,經(jīng)...
    沈念sama閱讀 44,104評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡热某,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了胳螟。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片昔馋。...
    茶點(diǎn)故事閱讀 38,569評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖糖耸,靈堂內(nèi)的尸體忽然破棺而出秘遏,到底是詐尸還是另有隱情,我是刑警寧澤嘉竟,帶...
    沈念sama閱讀 34,254評論 4 328
  • 正文 年R本政府宣布邦危,位于F島的核電站,受9級特大地震影響舍扰,放射性物質(zhì)發(fā)生泄漏倦蚪。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,834評論 3 312
  • 文/蒙蒙 一边苹、第九天 我趴在偏房一處隱蔽的房頂上張望陵且。 院中可真熱鬧,春花似錦个束、人聲如沸慕购。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,725評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽脓钾。三九已至,卻和暖如春桩警,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背昌妹。 一陣腳步聲響...
    開封第一講書人閱讀 31,950評論 1 264
  • 我被黑心中介騙來泰國打工捶枢, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留握截,地道東北人。 一個月前我還...
    沈念sama閱讀 46,260評論 2 360
  • 正文 我出身青樓烂叔,卻偏偏與公主長得像谨胞,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蒜鸡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,446評論 2 348

推薦閱讀更多精彩內(nèi)容