Android SystemService介绍一

SystemService 干嘛的。

Android SystemService 是framework的一些对应功能的服务供其他模块和app 来调用。例如 BatteryService(用来获取电池属性,充电状态,百分比等),PowerManagerService(休眠,wakeup 等),TvInputManagerService(创建session,releaseSession 等)等都是常用的系统服务,基本都是一个模块相关的功能在一个服务里面。

SystemService 的使用

使用比较简单,主要是通过 context.getSystemService(@NonNull Class<T> serviceClass)或者Object getSystemService(@ServiceName @NonNull String name) 获取一个manager 对象,去调用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 往往对应的有Manager ,app 通过获取Manager 调用Manager 里面的方法去调用到Service里面。

SystemService 和对应的Manager

Manager 和SystemService 通过AIDL 来进行通信。关系是
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); 
// 调用 到  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 调用 的代码

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 调用到 IBinder b 里面。
IBinder b = ServiceManager.getService(Context.DEVICE_STATE_SERVICE);
publishBinderService 与 ServiceManager.getService 相对应。这样DeviceStateManager 通过DeviceStateManagerGlobal 获取到DeviceStateManager Service对应的IBinder,同归aidl 调用到DeviceStateManagerService 里面。DeviceStateManager 暴露给app 来调用。

SystemService 和对应的Manager 的初始化

SystemServer 是由 Zygote ( Zygote 是啥干啥的,怎么启动 )分裂出来的第一个java进程,SystemService 和对应的Manager都是在 SystemServer 初始化

SystemServer {
    public static void main(String[] args) {
        new SystemServer().run();
    }
···
    private void run() {
···
         SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
···
         mSystemServiceManager = new SystemServiceManager(mSystemContext);
        startBootstrapServices(t); // 启动应的 SystemServices
           ···
        startCoreServices(t);// 启动应的 SystemServices
          ···
       startOtherServices(t);// 启动应的 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 的对应的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 进程初始化的时候 run方法 对SystemService 进行了初始化。
publishBinderService调用到ServiceManager(ServiceManager 是干嘛的,有啥用,跟进程间通信的关系)的 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 的实现都是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 方法 调用到SystemServiceRegistry,他的static 代码块就会自动调用到。
SystemServiceRegistry static 代码块里面对各个Manager 进行了初始化(或者叫声明初始化)。

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 当context 获取的时候就调用到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 有两个特点,1 cache 缓存 不重复创建 2 Fetcher 等到用的时候在创建,类似于懒加载。
ContextImpl 里面就是通过 SystemServiceRegistry.getSystemService 获取Manager

ContextImpl {
···
  @Override
    public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }
···
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容