Check network connection in fragment

随声附和 提交于 2019-11-27 06:31:49

问题


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

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
    }

Thanks in advance


回答1:


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
}

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.

Cheers!




回答2:


The better way is to use network function code in try- catch. And catch the exception If network unavailable. If you use any network checking code, then also you need to catch the exception. Because You have no other way to check whether it is suceeded or no, means, if the network lost in between the function completes.



来源:https://stackoverflow.com/questions/16481334/check-network-connection-in-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!