检查设备是否具有互联网连接
将所需的网络权限添加到应用程序清单文件:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
/**
* If network connectivity is available, will return true
*
* @param context the current context
* @return boolean true if a network connection is available
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Log.d("NetworkCheck", "isNetworkAvailable: No");
return false;
}
// get network info for all of the data interfaces (e.g. WiFi, 3G, LTE, etc.)
NetworkInfo[] info = connectivity.getAllNetworkInfo();
// make sure that there is at least one interface to test against
if (info != null) {
// iterate through the interfaces
for (int i = 0; i < info.length; i++) {
// check this interface for a connected state
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
Log.d("NetworkCheck", "isNetworkAvailable: Yes");
return true;
}
}
}
return false;
}