Search code examples
androiddual-sim

Dual SIM check internet connection issue


I use this code to check if internet network is on:

public boolean isNetworkOnline() {
        boolean status=false;
        try{
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getNetworkInfo(0);
            if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
                status= true;
            }else {
                netInfo = cm.getNetworkInfo(1);
                if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
                    status= true;
            }
        }catch(Exception e){
            e.printStackTrace();  
            return false;
        }
        return status;

        }

The problem is that if you use internet 3g from the SIM 2, this says that you do not have internet connection on.


Solution

  • Try the following code:

    public static boolean isNetworkAvailable(Context context) {
            boolean outcome = false;
    
    
            if (context != null) {
                ConnectivityManager cm = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
    
                NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
    
                for (NetworkInfo tempNetworkInfo : networkInfos) {
    
                    if (tempNetworkInfo.isConnected()) {
                        outcome = true;
                        break;
                    }
                }
            }
    
            return outcome;
        }