【问题标题】:How to properly get an instance of WifiManager in MainActivity and Fragment如何在 MainActivity 和 Fragment 中正确获取 WifiManager 的实例
【发布时间】:2016-03-30 04:35:44
【问题描述】:

根据WifiManager你的Android文档:

通过调用 Context.getSystemService(Context.WIFI_SERVICE) 获取此类的实例。


FragmentMainActivity 调用中:

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

返回错误:

无法从静态上下文引用非静态方法“getSystemService(java.lang.String)”。


MainActivity调用中:

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

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

有人能帮我理解为什么我们不再需要在Context 前加上前缀getSystemService(),即使该方法属于Context 类。另外,我们为什么要投射到(WifiManager)?这个解释将极大地帮助我,因为这不是第一次工作与文档规定的不同。


Fragment中调用相同的:

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

返回错误:

无法解析方法'getSystemService(java.lang.String)'


由于我在上一个post 中描述的问题,我希望能够获取片段中的实例。


【问题讨论】:

    标签: java android android-fragments android-studio wifimanager


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      警告那些正在寻找Activity 而不是FragmentWifiManager 的解决方案的人应该使用以下方法检索:

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

      在应用程序级别持有 WifiManager 相对于上下文以外的上下文将导致内存泄漏。

      来自Android Developer Docs

      Build.VERSION_CODES.N 之前的版本中,此对象应仅 从Context#getApplicationContext() 获得,而不是从任何 其他派生上下文以避免调用中的内存泄漏 过程。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-19
        • 1970-01-01
        • 2019-06-14
        • 2013-09-07
        • 1970-01-01
        • 2019-08-11
        • 1970-01-01
        相关资源
        最近更新 更多