检查片段的网络连接

检查片段的网络连接

本文介绍了检查片段的网络连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查我的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.

干杯!

这篇关于检查片段的网络连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:07