检测网络变化(wifi、2g、3g、4g)

时间:2023-11-25 11:45:14

检测网络变化(wifi、2g、3g、4g)

1.注册广播"android.net.conn.CONNECTIVITY_CHANGE"和"android.net.wifi.STATE_CHANGE" 进行监听:
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try
{
String action = intent.getAction();
Log.e("ConnectivityBroadcastReceiver", "action= "+action);
if ((!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
&& !action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION))
|| !isListening_) {
return;
} if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
networkInfo_ = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(networkInfo_.isConnected()) {
// WIFI is connected
state_ = NET_STATE_WIFI_CONNECTED;
}else{
state_ = NET_STATE_DISCONNECTED;
}
} else if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
networkInfo_ = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
String apn = networkInfo_.getExtraInfo();
Log.e("ConnectivityBroadcastReceiver", "apn= "+apn);
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if(networkInfo_.getType() == ConnectivityManager.TYPE_WIFI){
if ( networkInfo_.isConnected() ){
state_ = NET_STATE_WIFI_CONNECTED;
}else{
state_ = noConnectivity ? NET_STATE_DISCONNECTED : NET_STATE_WIFI_CONNECTED;
}
}else if(networkInfo_.getType() == ConnectivityManager.TYPE_MOBILE){
if (noConnectivity) {
state_ = NET_STATE_DISCONNECTED;
} else {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int type = telephonyManager.getNetworkType();
Log.e("ConnectivityBroadcastReceiver", "type= "+type);
state_ = getNetworkClass(type);
}
}else {
if (noConnectivity) {
state_ = NET_STATE_DISCONNECTED;
} else {
state_ = NET_STATE_UNKNOWN;
}
}
}
NotifyEvent();
}
catch (Exception e)
{
e.printStackTrace();
} }
};

2.判断TYPE_MOBILE下的网络类型:

private int getNetworkClass(int networkType) {
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return NET_STATE_2G_CONNECTED;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return NET_STATE_3G_CONNECTED;
case TelephonyManager.NETWORK_TYPE_LTE:
return NET_STATE_4G_CONNECTED;
default:
return NET_STATE_UNKNOWN;
}
}

3.在AndroidManifest.xml中加上权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>