从我的活动中调用getSystemService()时正在运行什么代码?

时间:2013-02-16 20:13:27

标签: android android-source

我正在尝试从grepcode site跟踪AOSP代码。

当我致电getSystemService(Context.WIFI_P2P_SERVICE)时,会转到以下代码:

 @Override public Object getSystemService(String name) {
    if (getBaseContext() == null) {
        throw new IllegalStateException(
                "System services not available to Activities before onCreate()");
    }
    if (WINDOW_SERVICE.equals(name)) {
        return mWindowManager;
    } else if (SEARCH_SERVICE.equals(name)) {
        ensureSearchManager();
        return mSearchManager;
    }
    return super.getSystemService(name);
}

自从WIFI_P2P_SERVICE声明为public static final String WIFI_P2P_SERVICE = "wifip2p";后,如果不属于其中一个条件,则会转到super.getSystemService(name);

Activity extends ContextThemeWrapper, the code there is:
 @Override public Object getSystemService(String name) {
        if (LAYOUT_INFLATER_SERVICE.equals(name)) {
            if (mInflater == null) {
                mInflater = LayoutInflater.from(mBase).cloneInContext(this);
            }
            return mInflater;
        }
        return mBase.getSystemService(name);
    }

此处,所需的服务名称也不匹配,mBaseContext的实例,因此Context中的代码为:

public abstract Object getSystemService(String name);

这意味着从中扩展的类必须处理该功能。 嗯,我的请求在哪里?

1 个答案:

答案 0 :(得分:2)

据我所知,Context的实现代码在android.app包下,类名为ContextImpl

这是来自该类的getSystemService -

@Override
public Object getSystemService(String name) {
    ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
    return fetcher == null ? null : fetcher.getService(this);
}

编辑 - WIFI_P2P_SERVICE的入口点 -

registerService(WIFI_P2P_SERVICE, new ServiceFetcher() {
    public Object createService(ContextImpl ctx) {
          IBinder b = ServiceManager.getService(WIFI_P2P_SERVICE);
          IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(b);
          return new WifiP2pManager(service);
        }});