首先需要添加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
判断是否有网络的代码:
public boolean isNetworkAvailable() { Context context = getApplicationContext(); ConnectivityManager connect = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connect == null) { return false; } else {// get all network info NetworkInfo[] info = connect.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }
或者
public boolean isNetworkAvailable() { Context context = getApplicationContext(); ConnectivityManager connect = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connect == null) { return false; } else { return connect.getActiveNetworkInfo().isAvailable(); } }