检查片段的网络连接片段、网络

2023-09-07 01:46:13 作者:疏影横斜水清浅

我想检查我的SherlockFragment网络连接,但getSystemService()方法无法识别。

I tried to check the network connection in my SherlockFragment but the getSystemService() method is not recognized.

下面是我的code(从的http://开发商.android.com /培训/基础/​​网络-OPS / connecting.html )

Below is my code (from http://developer.android.com/training/basics/network-ops/connecting.html)

    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
    } else {
        // display error
    }

在此先感谢

推荐答案

方法 getSystemService()上没有碎片的定义,所以得到的活性首先使用 getActivity(),例如:

The method getSystemService() is not defined on fragments, so get the activity first using getActivity(), e.g.:

ConnectivityManager connMgr = (ConnectivityManager) getActivity()
                             .getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isConnected()) {
    // fetch data
} else {
    // display error
}

PS : additianal笔记的:如果该片段不被连接到任何活动运行的潜在风险,检查是否 getActivity( )返回第一。

p.s: additianal note: if there is a potential risk that the fragment is running without being attached to any activity, check whether getActivity() returns null first.

干杯!