2

Currently I am looking for a concrete solution for getting the Cellular Network availability. For this I want share a scenario: Suppose I am getting Cellular connection but data connection is disabled in that case it should give me positive result but while I am out of coverage area or airplane mode is ON it should return false. I have tried few codes from stackoverflow :like Check Network connections in android and Check mobile network connectivity & What does NetworkInfo.State SUSPENDED indicate? but still they are not what I am looking for. Few of the other codes I tried are :

public String getCellularState(Context context){

           if(mPhoneState!=null &&   mPhoneState.getState()==ServiceState.STATE_IN_SERVICE){
            return "Available";
        }
        else{
            return "Not Available";
        }
}

and also

public String getOperator()
     { 
        TelephonyManager manager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
          opeartorName = manager.getSimOperator();
          return opeartorName; 
     }

but got no success, Please suggest the right way and also don't relate this to Data Connection

Community
  • 1
  • 1
Coder atpace
  • 49
  • 2
  • 7

4 Answers4

0

Check out this method (it returns true if you are connected to a network):

public static boolean checkConnectivity(Context ctx) {
        boolean bConectado = false;
        ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] redes = connec.getAllNetworkInfo();

        for (int i = 0; i < 2; i++) {
            if (redes[i].getState() == NetworkInfo.State.CONNECTED) {
                bConectado = true;
            }
        }
        return bConectado;
    }

I think that it is from other post from Stack Overflow, but I don't remember the link.

To view if you have a real connectivity, you can check it through a ping to Google DNS for example (How to Ping External IP from Java Android):

public static boolean executeCammand(){
        System.out.println(" executeCammand");
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue "+mExitValue);
            if(mExitValue==0){
                return true;
            }else{
                return false;
            }
        }
        catch (InterruptedException ignore)
        {
            ignore.printStackTrace();
            System.out.println(" Exception:"+ignore);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            System.out.println(" Exception:"+e);
        }
        return false;
    }

But in my opinion, this is not the best choice.

Community
  • 1
  • 1
adlagar
  • 877
  • 10
  • 31
0

Please check following and modify as per requirement :

public boolean getNetworkState() {
    boolean network = false;
    boolean data = false;
    ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] infos = connectivity.getAllNetworkInfo();
    for (int i = 0; i < infos.length; i++) {
        if(infos[i].isAvailable()){
            network = true;
        }
        if(infos[i].isConnected()){
            data = true;
        }   
    }

    if(network)
        if(!data)
            return true;

    return false;
}

If one of network is present and data connection not active then it will return true otherwise false. isAvailable will return network availability and isConnected will return data conncetivity.

Satty
  • 1,352
  • 1
  • 12
  • 16
0
/**
 * Checking whether internet connection is available or not using wifi as well as mobile data network.
 * 
 * @param nContext
 * @return true if net connection is avaible otherwise false
 */
public static boolean isNetworkAvailable(Context nContext) {
    boolean isNetAvailable = false;
    if (nContext != null) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) nContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (mConnectivityManager != null) {
            boolean mobileNetwork = false;
            boolean wifiNetwork = false;
            boolean mobileNetworkConnecetd = false;
            boolean wifiNetworkConnecetd = false;
            NetworkInfo mobileInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mobileInfo != null)
                mobileNetwork = mobileInfo.isAvailable();
            if (wifiInfo != null)
                wifiNetwork = wifiInfo.isAvailable();
            if (wifiNetwork == true || mobileNetwork == true) {
                if (mobileInfo != null)
                    mobileNetworkConnecetd = mobileInfo
                            .isConnectedOrConnecting();
                wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
            }
            isNetAvailable = (mobileNetworkConnecetd || wifiNetworkConnecetd);
        }
    }
    return isNetAvailable;

}
Utsav
  • 1
  • 2
  • just a sidenote: consider to not neglect the curly braces around if-statements even for simple ones. The reader has to figure out if your code is properly intented or not. – sschrass Apr 08 '15 at 11:15
  • @SatelliteSD : Can you pls guide me about your note? i mean to say line number... – Utsav Apr 30 '15 at 04:11
0

try this

public class ConnectionDetector {
    private static Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    public static boolean isConnectingToInternet(){ boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;}//here is change to take which we want

}
add these permissions in manifest file

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
Bapusaheb Shinde
  • 839
  • 2
  • 13
  • 16