(一)PowerManager
安卓系统级服务分析
标签(空格分隔): power PowerManager
如何获取一个Powermanager:
PowerManager power = (PowerManager) getSystemService(Context.POWER_SERVICE);
- PowerManager 实际上使用的是代理模式,这个可以来看它的构造函数和调用的函数
/**
* 构造函数 使用的是一个context, 一个powerService,和一个handler
* {@hide}
*/
public PowerManager(Context context, IPowerManager service, Handler handler) {
mContext = context;
mService = service;
mHandler = handler;
}
- 构造函数中的context实际上是用来帮助PowerManager来获取一些指定的参数的
/**
* Gets the minimum supported screen brightness setting.
* The screen may be allowed to become dimmer than this value but
* this is the minimum value that can be set by the user.
* @hide
*/
public int getMinimumScreenBrightnessSetting() {
return mContext.getResources().getInteger(
com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
}
- 构造函数中的service才是PowerManager方法的实际值行者
public void goToSleep(long time, int reason, int flags) {
try {
mService.goToSleep(time, reason, flags);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
- 而构造函数中的handler仅仅是用来执行一些延时任务
上面解析了PowerManager文件类,下面看为什么通过context可以获取PowerManager
通过Context获取PowerManager
PowerManager power = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
- 通过Context配合一个服务的名字来获取当前的某个系统服务,Context是一个抽象类,因此,需要找到Context的实现类来找到这个方法的实现,但目前我们知道Context的实现类是ContextImpl(这个细节我们之后在研究,在framework的研究过程中我们大多或采用这种方法,由于framework东西太多,有时候我们需要忽略某些与我们当前探究方向无关(或暂时无法探究)的东西,疑问可以保留 )
ContextImpl
ContextImpl中有一个成员变量,mServiceCache
final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();
@Override
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
@Override
public String getSystemServiceName(Class<?> serviceClass) {
return SystemServiceRegistry.getSystemServiceName(serviceClass);
}
- 由上面的代码可以看到,ContextImpl中的getSystemService也是通过SystemServiceRegistry来取到的, 而PowerManager在SystemServiceRegistry的静态代码块中进行了注册,SystemServiceRegitsry实际上管理的是系统服务的代理端,通过getSystemServcie接口来向外提供获得系统服务的能力
private static final HashMap<Class<?>, String> SYSTEM_SERVICE_NAMES =
new HashMap<Class<?>, String>();
private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS = new HashMap<String, ServiceFetcher<?>>();
registerService(Context.POWER_SERVICE, PowerManager.class,
new CachedServiceFetcher<PowerManager>() {
@Override
public PowerManager createService(ContextImpl ctx) {
//从这里我么你可以看到PowerManager的实现类是怎么获取到的。
IBinder b = ServiceManager.getService(Context.POWER_SERVICE);
IPowerManager service = IPowerManager.Stub.asInterface(b);
if (service == null) {
Log.wtf(TAG, "Failed to get power manager service.");
}
return new PowerManager(ctx.getOuterContext(),
service, ctx.mMainThread.getHandler());
}});
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);
}
/**
* 获取系统服务的实际操作者还是ServcieFetcher
* Gets a system service from a given context.
*/
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
接下来就要看ServceManager如何获取系统服务的实际执行对象了
整个ServiceManager的代码也没有多少,这个SerViceManager是通过获取ServiceManagerNative来管理Serivice的
package android.os;
import com.android.internal.os.BinderInternal;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
/** @hide */
public final class ServiceManager {
private static final String TAG = "ServiceManager";
private static IServiceManager sServiceManager;
//自己缓存了一个系统服务binder的列表,
private static HashMap<String, IBinder> sCache = new HashMap<String, IBinder>();
private static IServiceManager getIServiceManager() {
if (sServiceManager != null) {
return sServiceManager;
}
// Find the service manager
sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
return sServiceManager;
}
/**
* Returns a reference to a service with the given name.
*
* @param name the name of the service to get
* @return a reference to the service, or <code>null</code> if the service doesn't exist
*/
public static IBinder getService(String name) {
try {
//获取服务首先从缓存中获取,如果缓存中没有,
IBinder service = sCache.get(name);
if (service != null) {
return service;
} else {
//如果缓存中没有那么就从ServcieManagerNative中获取
return getIServiceManager().getService(name);
}
} catch (RemoteException e) {
Log.e(TAG, "error in getService", e);
}
return null;
}
/**
* Place a new @a service called @a name into the service
* manager.
*
* @param name the name of the new service
* @param service the service object
*/
public static void addService(String name, IBinder service) {
try {
getIServiceManager().addService(name, service, false);
} catch (RemoteException e) {
Log.e(TAG, "error in addService", e);
}
}
/**
* Place a new @a service called @a name into the service
* manager.
*
* @param name the name of the new service
* @param service the service object
* @param allowIsolated set to true to allow isolated sandboxed processes
* to access this service
*/
public static void addService(String name, IBinder service, boolean allowIsolated) {
try {
getIServiceManager().addService(name, service, allowIsolated);
} catch (RemoteException e) {
Log.e(TAG, "error in addService", e);
}
}
/**
* Retrieve an existing service called @a name from the
* service manager. Non-blocking.
*/
public static IBinder checkService(String name) {
try {
IBinder service = sCache.get(name);
if (service != null) {
return service;
} else {
return getIServiceManager().checkService(name);
}
} catch (RemoteException e) {
Log.e(TAG, "error in checkService", e);
return null;
}
}
/**
* Return a list of all currently running services.
* @return an array of all currently running services, or <code>null</code> in
* case of an exception
*/
public static String[] listServices() {
try {
return getIServiceManager().listServices();
} catch (RemoteException e) {
Log.e(TAG, "error in listServices", e);
return null;
}
}
/**
* This is only intended to be called when the process is first being brought
* up and bound by the activity manager. There is only one thread in the process
* at that time, so no locking is done.
*
* @param cache the cache of service references
* @hide
*/
public static void initServiceCache(Map<String, IBinder> cache) {
//从这个方法来看,应该是外部调用此方法来对sCache来进行初始化,以保证可以获取大部分的ServiceBinder,并且这个方法只能调用一次,如果多次调用就直接抛出异常
if (sCache.size() != 0) {
throw new IllegalStateException("setServiceCache may only be called once");
}
sCache.putAll(cache);
}
}
看到ServcieManager的方法之后我们就存在 三个疑问:
- 是谁调用了initServcieCache来对sCache来进行初始化的呢?
- addService方法是那些地方调用的?
- ServcieManagerNative是怎么实现 addServcie和getService这些方法的?
(二)SystemServer
上面的第一个问题 我在查源码的时这个方法的调用地点在ActivityThread中的bindApplication方法中,这个方法暂时还不清楚,因此 在此忽略,留到后面进行处理
关于第二个问题可以查到的地方就有:
- services/java/com/android/server/SystemServer.java
- services/core/java/com/android/server/AppOpsService.java
- services/core/java/com/android/server/telecom/TelecomLoaderService.java
- services/core/java/com/android/server/am/BatteryStatsService.java
- services/core/java/com/android/server/am/ActivityManagerService.java
- services/core/java/com/android/server/SystemService.java
- services/core/java/com/android/server/pm/PackageManagerService.java
- services/core/java/com/android/server/pm/OtaDexoptService.java
- services/core/java/com/android/server/connectivity/PacManager.java
其实主要的调用就在SystemServer中,SystemServer中有一个run方法这个方法在系统启动的时候会执行:
通过run方法启动一系列的系统服务
执行准备,创建一个SystemServiceManager,使用这个SystemServiceManager来启动相应的程序,
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Start services.
try {
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
//启动bootsrrap服务
//这里面启动了包括 PowerManagerService , ActivityManagerService,Install, 等一系列的服务,同时也启动一系列的传感器服务
startBootstrapServices();
//启动核心服务
startCoreServices();
//启动其他的服务
startOtherServices();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
---
上面的`startBoostrapServices`方法中有一个启动PowerManagerService的动作
private void startBootstrapServices() {
...
//电源管理 需要启动的比较早,因为其他服务对这个服务存在依赖。
// Power manager needs to be started early because other services need it.
// Native daemons may be watching for it to be registered so it must be ready
// to handle incoming binder calls immediately (including being able to verify
// the permissions for those calls).
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
// Now that the power manager has been started, let the activity manager 电源管理已经启动,现在让ams来进行进一步的初始化
// initialize power management features.
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitPowerManagement");
mActivityManagerService.initPowerManagement();
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
...}
使用SystemServiceManager来启动pwoerManagerService,并且调用了启动service的onStart方法,而powerManagerServcie的onstart方法中 调用了相应的方法把一个binder添加进去,PowerManager通过Binder调用PowerManagerService中的方法。 看下PowerManagerService的启动,从中就能找到 PowerManagerService是如何添加到SystemServer中的。