1 常用系统服务
1.1 ConnectivityManager网络连接的服务
常用来判断网络是否可用,当前网络类型如:WIFI、4G、3G、2G等。
简单举例 移步工具类--NetworkUtil
/**
* 获取可用的网络信息
*
* @param context
* @return
*/
private static NetworkInfo getActiveNetworkInfo(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo();
} catch (Exception e) {
return null;
}
}
/**
* 判断是否有网络可用
*
* @param context
* @return
*/
public static boolean isNetAvailable(Context context) {
NetworkInfo networkInfo = getActiveNetworkInfo(context);
if (networkInfo != null) {
return networkInfo.isAvailable();
} else {
return false;
}
}
1.2 NotificationManager状态栏的服务
//8.0 定位前台服务通知
private final static int GRAY_SERVICE_ID = -1002;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//这里启动一个后台notification,前台运行
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String id = "ipc";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(id, "ipc", importance);
mNotificationManager.createNotificationChannel(mChannel);
Notification notification = new Notification.Builder(context, id)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setContentTitle("IPC")
.setContentText("IPC通知")
.setAutoCancel(false)
.build();
//mNotificationManager.notify(GRAY_SERVICE_ID, notification);
startForeground(GRAY_SERVICE_ID, notification);
} else {
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("IPC")
//设置内容
.setContentText("IPC通知")
//设置小图标
.setSmallIcon(R.mipmap.ic_launcher)
//设置通知时间
.setWhen(System.currentTimeMillis())
//首次进入时显示效果
.setTicker("IPC通知--------------")
//设置通知方式,声音,震动,呼吸灯等效果,这里通知方式为声音
.setDefaults(Notification.DEFAULT_SOUND);
//mNotificationManager.notify(GRAY_SERVICE_ID, builder.build());
startForeground(GRAY_SERVICE_ID, notification);
}
1.3 PowerManager锁屏保持运行
//获取电源锁,保持该服务在屏幕熄灭时仍然获取CPU时,保持运行
private void acquireWakeLock() {
if (null == wakeLock) {
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
if (null != wakeLock) {
wakeLock.acquire();
}
}
}
//释放设备电源锁
private void releaseWakeLock() {
if (null != wakeLock) {
wakeLock.release();
wakeLock = null;
}
}
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.DEVICE_POWER"/>
第一个方法是获取锁,第二个方法是释放锁,一旦获取锁后,及时屏幕在熄灭或锁屏长时间后,系统后台一直可以保持获取到锁的应用程序运行。获取到PowerManager的实例pm后,再通过newWakeLock方法获取wakelock的实例,其中第一个参数是指定要获取哪种类型的锁,不同的锁对系统CPU、屏幕和键盘有不同的影响,第二个参数是自定义名称。
1.4 系统相应服务
getSystemService是Android很重要的一个API,根据传入的NAME来取得对应的Object,然后转换成相应的服务对象。
传入的Name | 返回的对象 | 说明 |
---|---|---|
WINDOW_SERVICE | WindowManager | 管理打开的窗口程序 |
LAYOUT_INFLATER_SERVICE | LayoutInflater | 取得xml里定义的view |
ACTIVITY_SERVICE | ActivityManager | 管理应用程序的系统状态 |
POWER_SERVICE | PowerManger | 电源的服务 |
ALARM_SERVICE | AlarmManager | 闹钟的服务 |
NOTIFICATION_SERVICE | NotificationManager | 状态栏的服务 |
KEYGUARD_SERVICE | KeyguardManager | 键盘锁的服务 |
LOCATION_SERVICE | LocationManager | 位置的服务,如GPS |
SEARCH_SERVICE | SearchManager | 搜索的服务 |
VEBRATOR_SERVICE | Vebrator | 手机震动的服务 |
CONNECTIVITY_SERVICE | ConnectivityManager | 网络连接的服务 |
WIFI_SERVICE | WifiManager | Wi-Fi服务 |
TELEPHONY_SERVICE | TeleponyManager | 电话服务 |
2 获取服务端的ServiceManager的service--getSystemService追踪
2.1 ContextImpl.getSystemService
[ContextImpl.java]
@Override
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
2.2 SystemServiceRegistry.getSystemService
[SystemServiceRegistry.java]
2.2.1 加载SystemServiceRegistry类
类加载机制
初始化静态变量和静态代码块
// Service registry information.
// This information is never changed once static initialization has completed.
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<?>>();
//维护注册各种服务service,这里只选出上述几个serviceName
static {
registerService(Context.CONNECTIVITY_SERVICE, ConnectivityManager.class,
new StaticApplicationContextServiceFetcher<ConnectivityManager>() {
@Override
public ConnectivityManager createService(Context context) throws ServiceNotFoundException {
IBinder b = ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE);
IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
return new ConnectivityManager(context, service);
}});
registerService(Context.NOTIFICATION_SERVICE, NotificationManager.class,
new CachedServiceFetcher<NotificationManager>() {
@Override
public NotificationManager createService(ContextImpl ctx) {
final Context outerContext = ctx.getOuterContext();
return new NotificationManager(
new ContextThemeWrapper(outerContext,
Resources.selectSystemTheme(0,
outerContext.getApplicationInfo().targetSdkVersion,
com.android.internal.R.style.Theme_Dialog,
com.android.internal.R.style.Theme_Holo_Dialog,
com.android.internal.R.style.Theme_DeviceDefault_Dialog,
com.android.internal.R.style.Theme_DeviceDefault_Light_Dialog)),
ctx.mMainThread.getHandler());
}});
registerService(Context.POWER_SERVICE, PowerManager.class,
new CachedServiceFetcher<PowerManager>() {
@Override
public PowerManager createService(ContextImpl ctx) throws ServiceNotFoundException {
IBinder b = ServiceManager.getServiceOrThrow(Context.POWER_SERVICE);
IPowerManager service = IPowerManager.Stub.asInterface(b);
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);
}
在registerService中将ServiceFetcher添加到SYSTEM_SERVICE_FETCHERS。
2.2.2 SystemServiceRegistry.getSystemService
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
2.2.3 fetcher.getService(ctx)
根据上面初始化,每个根据serviceName取出的fetcher会根据静态代码块中的fetcher去调用。
下面分别看看上述三个fetcher的get.service
fetcher都是SystemServiceRegistry的静态内部类
static abstract class StaticApplicationContextServiceFetcher<T> implements ServiceFetcher<T> {
private T mCachedInstance;
@Override
public final T getService(ContextImpl ctx) {
synchronized (StaticApplicationContextServiceFetcher.this) {
if (mCachedInstance == null) {
Context appContext = ctx.getApplicationContext();
// If the application context is null, we're either in the system process or
// it's the application context very early in app initialization. In both these
// cases, the passed-in ContextImpl will not be freed, so it's safe to pass it
// to the service. http://b/27532714 .
try {
mCachedInstance = createService(appContext != null ? appContext : ctx);
} catch (ServiceNotFoundException e) {
onServiceNotFound(e);
}
}
return mCachedInstance;
}
}
public abstract T createService(Context applicationContext) throws ServiceNotFoundException;
}
static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> {
private final int mCacheIndex;
public CachedServiceFetcher() {
mCacheIndex = sServiceCacheSize++;
}
@Override
@SuppressWarnings("unchecked")
public final T getService(ContextImpl ctx) {
final Object[] cache = ctx.mServiceCache;
synchronized (cache) {
// Fetch or create the service.
Object service = cache[mCacheIndex];
if (service == null) {
try {
service = createService(ctx);
cache[mCacheIndex] = service;
} catch (ServiceNotFoundException e) {
onServiceNotFound(e);
}
}
return (T)service;
}
}
public abstract T createService(ContextImpl ctx) throws ServiceNotFoundException;
}
- 通过上面可以看出在getService中最初都是调用createService,而createService是在静态代码块中重写的。
2.2.4 POWER_SERVICE的createService
@Override
public PowerManager createService(ContextImpl ctx) throws ServiceNotFoundException {
IBinder b = ServiceManager.getServiceOrThrow(Context.POWER_SERVICE);
IPowerManager service = IPowerManager.Stub.asInterface(b);
return new PowerManager(ctx.getOuterContext(),
service, ctx.mMainThread.getHandler());
}});
2.2.4.1 ServiceManager.getServiceOrThrow(Context.POWER_SERVICE);
[ServiceManager.java]
public static IBinder getServiceOrThrow(String name) throws ServiceNotFoundException {
final IBinder binder = getService(name);
if (binder != null) {
return binder;
} else {
throw new ServiceNotFoundException(name);
}
}
这里直接调用ServiceManager的getService返回binder
详细请看Android跨进程通信IPC之18——Binder之Framework层Java篇--获取服务
2.2.4.2 IPowerManager.Stub.asInterface(b);
一看这个调用就是aidl
详细过程移步
Android跨进程通信IPC之19——AIDL
2.2.4.3 new PowerManager()
public PowerManager(Context context, IPowerManager service, Handler handler) {
mContext = context;
mService = service;
mHandler = handler;
}
只是做了一些赋值操作。
致此getSystemService完成
3 调用服务端的方法,以PowerManager为例使用
例子 1.3
private void acquireWakeLock() {
if (null == wakeLock) {
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
if (null != wakeLock) {
wakeLock.acquire();
}
}
}
直接看wakeLock.acquire()
其他细节不是咱么关注的重点。
3.1 wakeLock.acquire()
public void acquire() {
synchronized (mToken) {
acquireLocked();
}
}
3.2 acquireLocked()
private void acquireLocked() {
mInternalCount++;
mExternalCount++;
if (!mRefCounted || mInternalCount == 1) {
Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
try {
mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
mHistoryTag);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
mHeld = true;
}
}
最终使用 mService.acquireWakeLock()使用服务端的服务。
参考
# android servicemanager与binder源码分析二 ------ servicemanager服务提供者