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