public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Log.i("NetWorkState", "Unavailabel");
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
Log.i("NetWorkState", "Availabel");
return true;
}
}
}
}
return false;
}
上面这个方法就是判断网络是否连接的代码,返回true表示有网络,返回false表示无网络。 在Android网络应用程序开发中,经常要判断网络连接是否可用,因此经常有必要监听网络状态的变化。android的网络状态监听可以用BroadcastReceiver来接收网络状态改变的广 播,具体实现如下:
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "网络状态改变");
boolean success = false;
//获得网络连接服务
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
// State state = connManager.getActiveNetworkInfo().getState();
State state = connManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState(); // 获取网络连接状态
if (State.CONNECTED == state) { // 判断是否正在使用WIFI网络
success = true;
}
state = connManager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).getState(); // 获取网络连接状态
if (State.CONNECTED != state) { // 判断是否正在使用GPRS网络
success = true;
}
if (!success) {
Toast.makeText(LocationMapActivity.this, "您的网络连接已中断", Toast.LENGTH_LONG).show();
}
}
在Activity的onCreate中:
//注册网络监听
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver, filter);
//在Activity中的onDestroy中:
unregisterReceiver(mNetworkStateReceiver); //取消监听
AndroidManifest.xml
- 为了访问网络我们需要 INTERNET 权限
- 为了检查网络状态我们需要 ACCESS_NETWORK_STATE 权限
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />