问题阐述:
由某个系统service创建出来的对象,并用的这个对象通过getSystemService()函数去获取对应Service,发现总是为null。
解决办法
去SystemServer里面review你的逻辑,看看是否有对应service未起来的时候就通过getSystemService去获取了,这样会导致当前context的cache里面记录STATE_NOT_FOUND的flag,那么自此之后即使后来service起来了此Context也不会拿到这个service。
探索:
一般上述问题的出现是在对应service没起来的时候就去获取了,当然得不到,但是研究表明,此时的service已经起来,并不是这个的问题。
我们一般获取service都是通过context.getSystemService的,那我们看一下调用逻辑:
getSystemService()
-->
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
-->
public final T getService(ContextImpl ctx) {
final Object[] cache = ctx.mServiceCache;
final int[] gates = ctx.mServiceInitializ