You can use these 2 methods to detect the type of network:
public static boolean isConnectedWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
public static boolean isConnectedMobile(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
To determine the change, you can define two constants to define the two types of network:
private final static int WIFI_ACTIVA = 0 ;
private final static int MOVIL_ACTIVA = 1 ;
and another to determine the current active type and the last detected network:
private int RED_ACTIVA = 0 ;
private int ULTIMA_RED_ACTIVA = 0 ;
The BroadCastReceiver should constantly check the type:
if(isConnectedWifi(getApplicationContext()){
RED_ACTIVA = WIFI_ACTIVA;
}else if(isConnectedMobile(getApplicationContext()){
RED_ACTIVA = MOVIL_ACTIVA ;
}else{
RED_ACTIVA = -1; //No existe red activa WIFI o MOVIL.
}
In the end you simply compare the value of the last active network.
if(ULTIMA_RED_ACTIVA != RED_ACTIVA){
//RED ACTIVA CAMBIO!
switch(RED_ACTIVA) {
case WIFI_ACTIVA:
//RED ACTIVA CAMBIO A WIFI!
break;
case MOVIL_ACTIVA :
//RED ACTIVA CAMBIO A MOVIL!
break;
}
}
You store the value of the "last active network":
ULTIMA_RED_ACTIVA = RED_ACTIVA