创建一个 isNetworkAvailable 方法
public boolean isNetworkAvailable(AppCompatActivity appCompatActivity) {
Context context = appCompatActivity.getApplicationContext();
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
} else {
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0) {
for (int i = 0; i < networkInfo.length; i++) {
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
在需要判断网络的地方写下列代码
//isNetworkAvailable 参数为当前Activity.this
if (isNetworkAvailable(MainActivity.this)) {
Toast.makeText(getApplicationContext(), "当前有可用网络!", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "当前没有可用网络!", Toast.LENGTH_LONG).show();
}
AndroidManifest.xml 中添加访问当前网络状态权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>