public static final int NETWORK_TYPE_NONE = 0;
public static final int NETWORK_TYPE_2G = 2;
public static final int NETWORK_TYPE_3G = 3;
public static final int NETWORK_TYPE_4G = 4;
public static final int NETWORK_TYPE_WIFI = 10;
private String getNetType() {
int type = getNetworkType(mContext);
String netType = “”;
switch (type) {
case Utils.NETWORK_TYPE_NONE:
netType = “”;
break;
case Utils.NETWORK_TYPE_2G:
netType = “2G”;
break;
case Utils.NETWORK_TYPE_3G:
netType = “3G”;
break;
case Utils.NETWORK_TYPE_4G:
netType = “4G”;
break;
case Utils.NETWORK_TYPE_WIFI:
netType = “wifi”;
break;
}
return netType;
}

2.实时监听网络切换


实现监听网络的功能主要依靠 广播监听  。不多说 看代码。回调中逻辑改成自己的就可以了。

oncreate中 需要注册一下 广播

mNetworkReceiver = new NetTypeReceiver();
registerReceiver(mNetworkReceiver, intent);
ondestory中需要将广播销毁
if (mNetworkReceiver != null) {
unregisterReceiver(mNetworkReceiver);
mNetworkReceiver = null;
}
private class NetTypeReceiver extends BroadcastReceiver {
String type = “”;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
String name = networkInfo.getTypeName();
switch (networkInfo.getType()) {
case 0://移动 网络
if (TextUtils.isEmpty(type)) {
type = name;
}
break;
case 1:wifi网络
if (TextUtils.isEmpty(type)) {
type = name;
}
break;
}
} else {// 无网络
//network was unavailable, stop the streamer, and show a dialog
showNetworkInvalidView(R.string.network_error_message);
type = “”;
}
}
}
}