美文网首页
Android SystemService介绍一

Android SystemService介绍一

作者: 无敌之神将 | 来源:发表于2023-06-27 09:57 被阅读0次

    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);
        }
    ···
    }
    

    相关文章

      网友评论

          本文标题:Android SystemService介绍一

          本文链接:https://www.haomeiwen.com/subject/geieddtx.html