关于android.os.ServiceManager 这个类及源码中的问题
发布日期:2021-07-23 22:22:26
浏览次数:1
分类:技术文章
本文共 15851 字,大约阅读时间需要 52 分钟。
通过andorid studio 下载的源码貌似有些问题
下载地址:
里面的serviceManager类
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package android.os;import java.util.Map;public final class ServiceManager { /** * 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, ornull
if the service doesn't exist */ public static IBinder getService(String name) { return null; } /** * Is not supposed to return null, but that is fine for layoutlib. */ public static IBinder getServiceOrThrow(String name) throws ServiceNotFoundException { throw new ServiceNotFoundException(name); } /** * 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) { // pass } /** * Retrieve an existing service called @a name from the * service manager. Non-blocking. */ public static IBinder checkService(String name) { return null; } /** * Return a list of all currently running services. * @return an array of all currently running services, ornull
in * case of an exception */ public static String[] listServices() { // actual implementation returns null sometimes, so it's ok // to return null instead of an empty list. 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(Mapcache) { // pass } /** * Exception thrown when no service published for given name. This might be * thrown early during boot before certain services have published * themselves. * * @hide */ public static class ServiceNotFoundException extends Exception { // identical to the original implementation public ServiceNotFoundException(String name) { super("No service published for: " + name); } }}
可以看到,这套源码里面,serviceManager的很多方法都没有,实现
而通过
这个地址查看android.os.ServiceManager这个类可以发现是这样的
/*2 * Copyright (C) 2007 The Android Open Source Project3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */1617package android.os;1819import android.util.Log;2021import com.android.internal.annotations.GuardedBy;22import com.android.internal.os.BinderInternal;23import com.android.internal.util.StatLogger;2425import java.util.HashMap;26import java.util.Map;2728/** @hide */29public final class ServiceManager {30 private static final String TAG = "ServiceManager";31 private static final Object sLock = new Object();3233 private static IServiceManager sServiceManager;3435 /**36 * Cache for the "well known" services, such as WM and AM.37 */38 private static HashMapsCache = new HashMap ();3940 /**41 * We do the "slow log" at most once every this interval.42 */43 private static final int SLOW_LOG_INTERVAL_MS = 5000;4445 /**46 * We do the "stats log" at most once every this interval.47 */48 private static final int STATS_LOG_INTERVAL_MS = 5000;4950 /**51 * Threshold in uS for a "slow" call, used on core UIDs. We use a more relax value to52 * avoid logspam.53 */54 private static final long GET_SERVICE_SLOW_THRESHOLD_US_CORE =55 SystemProperties.getInt("debug.servicemanager.slow_call_core_ms", 10) * 1000;5657 /**58 * Threshold in uS for a "slow" call, used on non-core UIDs. We use a more relax value to59 * avoid logspam.60 */61 private static final long GET_SERVICE_SLOW_THRESHOLD_US_NON_CORE =62 SystemProperties.getInt("debug.servicemanager.slow_call_ms", 50) * 1000;6364 /**65 * We log stats logging ever this many getService() calls.66 */67 private static final int GET_SERVICE_LOG_EVERY_CALLS_CORE =68 SystemProperties.getInt("debug.servicemanager.log_calls_core", 100);6970 /**71 * We log stats logging ever this many getService() calls.72 */73 private static final int GET_SERVICE_LOG_EVERY_CALLS_NON_CORE =74 SystemProperties.getInt("debug.servicemanager.log_calls", 200);7576 @GuardedBy("sLock")77 private static int sGetServiceAccumulatedUs;7879 @GuardedBy("sLock")80 private static int sGetServiceAccumulatedCallCount;8182 @GuardedBy("sLock")83 private static long sLastStatsLogUptime;8485 @GuardedBy("sLock")86 private static long sLastSlowLogUptime;8788 @GuardedBy("sLock")89 private static long sLastSlowLogActualTime;9091 interface Stats {92 int GET_SERVICE = 0;9394 int COUNT = GET_SERVICE + 1;95 }9697 public static final StatLogger sStatLogger = new StatLogger(new String[] {98 "getService()",99 });100101 private static IServiceManager getIServiceManager() {102 if (sServiceManager != null) {103 return sServiceManager;104 }105106 // Find the service manager107 sServiceManager = ServiceManagerNative108 .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));109 return sServiceManager;110 }111112 /**113 * Returns a reference to a service with the given name.114 *115 * @param name the name of the service to get116 * @return a reference to the service, or null
if the service doesn't exist117 */118 public static IBinder getService(String name) {119 try {120 IBinder service = sCache.get(name);121 if (service != null) {122 return service;123 } else {124 return Binder.allowBlocking(rawGetService(name));125 }126 } catch (RemoteException e) {127 Log.e(TAG, "error in getService", e);128 }129 return null;130 }131132 /**133 * Returns a reference to a service with the given name, or throws134 * {@link NullPointerException} if none is found.135 *136 * @hide137 */138 public static IBinder getServiceOrThrow(String name) throws ServiceNotFoundException {139 final IBinder binder = getService(name);140 if (binder != null) {141 return binder;142 } else {143 throw new ServiceNotFoundException(name);144 }145 }146147 /**148 * Place a new @a service called @a name into the service149 * manager.150 *151 * @param name the name of the new service152 * @param service the service object153 */154 public static void addService(String name, IBinder service) {155 addService(name, service, false, IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT);156 }157158 /**159 * Place a new @a service called @a name into the service160 * manager.161 *162 * @param name the name of the new service163 * @param service the service object164 * @param allowIsolated set to true to allow isolated sandboxed processes165 * to access this service166 */167 public static void addService(String name, IBinder service, boolean allowIsolated) {168 addService(name, service, allowIsolated, IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT);169 }170171 /**172 * Place a new @a service called @a name into the service173 * manager.174 *175 * @param name the name of the new service176 * @param service the service object177 * @param allowIsolated set to true to allow isolated sandboxed processes178 * @param dumpPriority supported dump priority levels as a bitmask179 * to access this service180 */181 public static void addService(String name, IBinder service, boolean allowIsolated,182 int dumpPriority) {183 try {184 getIServiceManager().addService(name, service, allowIsolated, dumpPriority);185 } catch (RemoteException e) {186 Log.e(TAG, "error in addService", e);187 }188 }189190 /**191 * Retrieve an existing service called @a name from the192 * service manager. Non-blocking.193 */194 public static IBinder checkService(String name) {195 try {196 IBinder service = sCache.get(name);197 if (service != null) {198 return service;199 } else {200 return Binder.allowBlocking(getIServiceManager().checkService(name));201 }202 } catch (RemoteException e) {203 Log.e(TAG, "error in checkService", e);204 return null;205 }206 }207208 /**209 * Return a list of all currently running services.210 * @return an array of all currently running services, ornull
in211 * case of an exception212 */213 public static String[] listServices() {214 try {215 return getIServiceManager().listServices(IServiceManager.DUMP_FLAG_PRIORITY_ALL);216 } catch (RemoteException e) {217 Log.e(TAG, "error in listServices", e);218 return null;219 }220 }221222 /**223 * This is only intended to be called when the process is first being brought224 * up and bound by the activity manager. There is only one thread in the process225 * at that time, so no locking is done.226 *227 * @param cache the cache of service references228 * @hide229 */230 public static void initServiceCache(Mapcache) {231 if (sCache.size() != 0) {232 throw new IllegalStateException("setServiceCache may only be called once");233 }234 sCache.putAll(cache);235 }236237 /**238 * Exception thrown when no service published for given name. This might be239 * thrown early during boot before certain services have published240 * themselves.241 *242 * @hide243 */244 public static class ServiceNotFoundException extends Exception {245 public ServiceNotFoundException(String name) {246 super("No service published for: " + name);247 }248 }249250 private static IBinder rawGetService(String name) throws RemoteException {251 final long start = sStatLogger.getTime();252253 final IBinder binder = getIServiceManager().getService(name);254255 final int time = (int) sStatLogger.logDurationStat(Stats.GET_SERVICE, start);256257 final int myUid = Process.myUid();258 final boolean isCore = UserHandle.isCore(myUid);259260 final long slowThreshold = isCore261 ? GET_SERVICE_SLOW_THRESHOLD_US_CORE262 : GET_SERVICE_SLOW_THRESHOLD_US_NON_CORE;263264 synchronized (sLock) {265 sGetServiceAccumulatedUs += time;266 sGetServiceAccumulatedCallCount++;267268 final long nowUptime = SystemClock.uptimeMillis();269270 // Was a slow call?271 if (time >= slowThreshold) {272 // We do a slow log:273 // - At most once in every SLOW_LOG_INTERVAL_MS274 // - OR it was slower than the previously logged slow call.275 if ((nowUptime > (sLastSlowLogUptime + SLOW_LOG_INTERVAL_MS))276 || (sLastSlowLogActualTime < time)) {277 EventLogTags.writeServiceManagerSlow(time / 1000, name);278279 sLastSlowLogUptime = nowUptime;280 sLastSlowLogActualTime = time;281 }282 }283284 // Every GET_SERVICE_LOG_EVERY_CALLS calls, log the total time spent in getService().285286 final int logInterval = isCore287 ? GET_SERVICE_LOG_EVERY_CALLS_CORE288 : GET_SERVICE_LOG_EVERY_CALLS_NON_CORE;289290 if ((sGetServiceAccumulatedCallCount >= logInterval)291 && (nowUptime >= (sLastStatsLogUptime + STATS_LOG_INTERVAL_MS))) {292293 EventLogTags.writeServiceManagerStats(294 sGetServiceAccumulatedCallCount, // Total # of getService() calls.295 sGetServiceAccumulatedUs / 1000, // Total time spent in getService() calls.296 (int) (nowUptime - sLastStatsLogUptime)); // Uptime duration since last log.297 sGetServiceAccumulatedCallCount = 0;298 sGetServiceAccumulatedUs = 0;299 sLastStatsLogUptime = nowUptime;300 }301 }302 return binder;303 }304}305
这r3版本的源码,serviceManager里面的东西就都实现了。。。
===================================================
那么,serviceManager这个类主要是用来干嘛的呢,其实这个类是系统中的ServiceManager在java端的一个代理
看下SystemServiceRegister类中它干了什么就知道了,如下,很多service的代理都可以通过它得到
registerService(Context.CONNECTIVITY_SERVICE, ConnectivityManager.class, new StaticApplicationContextServiceFetcher() { @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.IPSEC_SERVICE, IpSecManager.class, new CachedServiceFetcher () { @Override public IpSecManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getService(Context.IPSEC_SERVICE); IIpSecService service = IIpSecService.Stub.asInterface(b); return new IpSecManager(ctx, service); }}); registerService(Context.COUNTRY_DETECTOR, CountryDetector.class, new StaticServiceFetcher () { @Override public CountryDetector createService() throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.COUNTRY_DETECTOR); return new CountryDetector(ICountryDetector.Stub.asInterface(b)); }}); registerService(Context.DEVICE_POLICY_SERVICE, DevicePolicyManager.class, new CachedServiceFetcher () { @Override public DevicePolicyManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.DEVICE_POLICY_SERVICE); return new DevicePolicyManager(ctx, IDevicePolicyManager.Stub.asInterface(b)); }});
转载地址:https://blog.csdn.net/perfectnihil/article/details/90914493 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月29日 13时49分43秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Spring IOC流程源码分析
2019-04-29
SpringIOC、DI、AOP、MVC总结、时序图
2019-04-29
spring循环依赖及解决方法
2019-04-29
Nginx反向代理负载均衡时,验证码不正确
2019-04-29
@EnableDiscoveryClient
2019-04-29
查看docker的端口映射情况
2019-04-29
Sentinel入门
2019-04-29
Sentinel的blockHandler与fallback的区别
2019-04-29
幂等性
2019-04-29
RPC和Restful深入理解
2019-04-29
layui.table.render设置自定义高度高度
2019-04-29
为nginx反向代理设置自定义错误页面
2019-04-29
使用nginx动静分离后,druid被拦截的解决方法
2019-04-29
Sentinel结合Fejgn接口,进行调用远程接口的调用和限流
2019-04-29
Unity之C#学习笔记(0):环境配置与上手 HelloWorld
2019-04-29
JDBC中的execute方法部分细节详解
2019-04-29
@Test有什么作用
2019-04-29
做项目的思路(该创建什么类)
2019-04-29
学代码必须要注意的三个点
2019-04-29