Algorithm in the change of Android network

1

Hi, I have a BroadcastReceiver that returns to me

Log.i("Network", "Network connected : " + ni.getTypeName()); WIFI o MOBILE

and another method that returns to me if WIFI is your

Log.i("Network", "Name " + ssid);

There is a method that should be checked if ni.getTypeName() is WIFI and suddenly changes to MOBILE and vice versa and if it is in WIFI and% SSID change also execute this method.

    
asked by JDeveloper 28.06.2016 в 18:05
source

2 answers

0

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
    
answered by 28.06.2016 / 21:29
source
1

If I understand the statement of your question well, this can help you.

link

    
answered by 28.06.2016 в 20:59