问题
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