如何在 MainActivity 和 Fragment 中正确获取 WifiManager 的实例

How to properly get an instance of WifiManager in MainActivity and Fragment

根据 WifiManager 的 Android 文档,您:

Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE).


FragmentMainActivity 中调用:

WifiManager wifiManager = Context.getSystemService(Context.WIFI_SERVICE);

returns 错误:

Non-static method 'getSystemService(java.lang.String)' cannot be referenced from a static context.


MainActivity中调用:

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

有效,但是为什么文档中另有说明?

谁能帮我理解为什么我们不再需要在 ContextgetSystemService() 前添加前缀,即使该方法属于 Context class。还有为什么我们要投射到 (WifiManager)?这个解释将对我有很大帮助,因为这不是第一次与文档规定的不同。


Fragment中调用相同的:

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

returns错误:

Cannot resolve method 'getSystemService(java.lang.String)'


由于我在上一篇 post.

中描述的问题,我希望能够在片段中获取实例

使用 getActivity() 方法从 Fragment 调用 getSystemService 方法,例如:

WifiManager wifiManager = (WifiManager) getActivity().
                         getSystemService(Context.WIFI_SERVICE);

因为getSystemService方法来自上下文class而不是Fragment

警告那些寻找 Activity 而不是 Fragment 的解决方案的人,应该使用以下方法检索 WifiManager

WifiManager wifiManager = mContext.getApplicationContext()
                                  .getSystemService(Context.WIFI_SERVICE);

将 WifiManager 保留在应用程序级别以外的上下文中会导致内存泄漏。

来自Android Developer Docs

On releases before Build.VERSION_CODES.N, this object should only be obtained from an Context#getApplicationContext(), and not from any other derived context to avoid memory leaks within the calling process.