<small>
在android开发中,对网络状态的监听是非常重要的。比如在WIFI情况下,加载高清的图片。在3G和4G的情况下加载图片质量比较差的图片。那么怎样对android网络状态进行监听呢?
首先加上需要加的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
然后我们就可以编写一个对网络状态进行判断的工具类:NetUtils
//网络是否可用
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = mgr.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
//网络是否连接
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
//是否是WIFI的情况下
public static boolean isWifiConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWiFiNetworkInfo != null) {
return mWiFiNetworkInfo.isAvailable();
}
}
return false;
}
//3G网络
public static boolean isMobileConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mMobileNetworkInfo != null) {
return mMobileNetworkInfo.isAvailable();
}
}
return false;
}
这个工具类用来判断网络的一些状态,然后我们需要一个广播接收者,来接收网络的变化
需要在AndroidManifest.xml文件中注册:
<receiver android:name=".NetStateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
</intent-filter>
</receiver>
最后就可以着手对网络变化进行监听了:
public class NetStateReceiver extends BroadcastReceiver {
private final static String ANDROID_NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(ANDROID_NET_CHANGE_ACTION)) {
if (NetUtils.isNetworkAvailable(context)) {
//Wifi情况下
if (NetUtils.isWifiConnected(context)) {
Log.d("same_info>>", "net wifi");
}
//数据流量的情况下
else {
Log.d("same_info>>", "net data");
}
} else {
Log.d("same_info>>", "net error");
}
}
}
}
<small>