14

My application is working perfect in wifi and mobile networks, but fails to detect when connected through bluetooth tethering.

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) 
      getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

I tried running a few other applications . they also shows no network connectivity, But google applications works perfect and so as some other apps like whatsap. Wondering how they are doing it, and why most of the applications missing this point..

Can anyone tell me a way to check the internet connectivity in android, through all means available,including bluetooth pan and proxy,etc.

Any help will be appreciated. Thanks in advance..

JIthin
  • 1,413
  • 1
  • 13
  • 29
  • check this http://stackoverflow.com/a/22668259/2811956 – W I Z A R D Jan 21 '15 at 04:29
  • it's to detect tethering status of bluetooth, not for checking network connectivity through it – JIthin Jan 21 '15 at 04:36
  • Just try to ping a web site like google, no matter where is the connection comes from. – M. Reza Nasirloo Jan 23 '15 at 09:26
  • These answers all miss: you should use ConnectivityManager.requestNetwork(), so it can turn on Wifi/Bluetooth/whatever if you need it. Simply checking for a connection doesn't help you if Android has disabled data, for instance. – phreakhead Mar 19 '16 at 00:17

7 Answers7

7

Try connecting to an "always available" website. if any connection exist, this should return true:

protected static boolean hasInternetAccess()
{
    try
    {
        URL url = new URL("http://www.google.com");

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application:1");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000 * 30);
        urlc.connect();

        // http://www.w3.org/Protocols/HTTP/HTRESP.html
        if (urlc.getResponseCode() == 200 || urlc.getResponseCode() > 400)
        {
            // Requested site is available
            return true;
        }
    }
    catch (Exception ex)
    {
        // Error while trying to connect
        return false;
    }
    return false;
}
Muzikant
  • 8,070
  • 5
  • 54
  • 88
  • nice idea and it's the simplest. It's practical. But I was trying to find the internet connectivity and also to to identify the mode of connection, Even though it may not be necessary, always. – JIthin Jan 29 '15 at 03:57
  • 1
    Does it worth the data consumption and waiting time for the ping to come back? Wouldn't it be easier to just check the phone connectivity state? – Fernando Carvalhosa Jan 30 '15 at 04:06
  • 2
    @FernandoCarvalhosa That depends on your case. The way I see it, in most cases waiting for the response to come back is not a problem (and usually, it returns in several milliseconds or even less when there is no connectivity). Checking the connectivity state does not provide an answer to the question "Do I have an Internet connection?" when you are connected to a wifi connection with no Internet access or when connected through Bluetooth – Muzikant Jan 30 '15 at 12:25
  • This is a terrible implementation – portfoliobuilder Aug 26 '15 at 19:32
4

may be this is helpful, getAllNetworkInfo() provide list of network info

 public boolean checkNetworkStatus(Context context) 
            {
                boolean flag = false;
                ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo[] netInfo = cm.getAllNetworkInfo();

               //it provide all type of connectivity ifo
                for (NetworkInfo ni : netInfo)
                {
                    if (ni.getTypeName().equalsIgnoreCase("Connecxtion Type"))
                        if (ni.isConnected())
                            flag = true;
                }
                return flag;
            }
Lokesh
  • 3,247
  • 2
  • 33
  • 62
3

The simplest way to detect if the phone (or any other device) has a connection to the internet is to send a ping to a webserver in my eyes. Of course you need an ip adress which in always reachable. You can try this code (out of my head) maybe you have to catch some exceptions:

public boolean hasInternetConection() {
    Runtime runtime = Runtime.getRuntime();
    Process ping = runtime.exec("/system/bin/ping -c 1 173.194.39.4"); // google.com

    int result = ping.waitFor();

    if(result == 0) return true;
    else return false;
}

Of course you have to run this method every time the wifi state, bluetooth state or somethin else changed (I would recommend in a seperate thread) but all in all it should work for your problem.

Cilenco
  • 6,951
  • 17
  • 72
  • 152
  • Nice and smallest way I think. I tried the command in adb shell, but it failed . Will try using code. Hope it works in all devices without rooting. – JIthin Jan 29 '15 at 03:59
  • It should work on every phone without root. Let me know if it helped you :) – Cilenco Jan 29 '15 at 16:38
  • Does it worth the data consumption and waiting time for the ping to come back? Wouldn't it be easier to just check the phone connectivity state? – Fernando Carvalhosa Jan 30 '15 at 04:05
3

You can use the following :

public boolean isMyNetworkIsLive() {
    boolean isConnectionActive = false;
    ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    if (nNetworkInfo != null && nNetworkInfo.isConnectedOrConnecting()) {
        isConnectionActive = true;
    }
    return isConnectionActive;
}

Ref from Test Internet Connection Android

Community
  • 1
  • 1
Bijesh P V
  • 798
  • 7
  • 14
3

Your internet connectivity check seems fine. About the bluetooth connectivity, try this:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
    // Bluetooth enabled
}  

Your perfect function would be something like:

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    return networkInfo != null && networkInfo.isConnected()
           bluetoothAdapter != null && bluetoothAdapter.isEnabled() 
}

I think you will need these permissions:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Fernando Carvalhosa
  • 1,098
  • 1
  • 15
  • 23
  • 1
    For Bluetooth connectivity - This only checks if Bluetooth is enabled but not if Bluetooth tethering is active. In all cases (Bluetooth, wifi, celluar network) this does not provide an answer to the question "Do I have an Internet connection?" since you may be connected to a wifi network that has no Internet connection (closed/private network, network that requires login etc...) – Muzikant Jan 30 '15 at 12:29
1

I agree with Muzikant and thanks for the idea. I thought it will be better to post the implemented solution as it needs some additions.

This is how I solved it.

Created and AsyncTask to avoid network on main thread exception.

public class GetInternetStatus extends AsyncTask<Void,Void,Boolean> {

@Override
protected Boolean doInBackground(Void... params) {

    return hasInternetAccess();
}

protected  boolean hasInternetAccess()
{

    try
    {
        URL url = new URL("http://www.google.com");

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application:1");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000 * 30);
        urlc.connect();

        // http://www.w3.org/Protocols/HTTP/HTRESP.html
        if (urlc.getResponseCode() == 200 || urlc.getResponseCode() > 400)
        {
            // Requested site is available
            return true;
        }
    }
    catch (Exception ex)
    {
        // Error while trying to connect
        ex.printStackTrace();
        return false;
    }
    return false;
}

}

Now add the following function to activity and call it to check the connectivity.

    // Checking for all possible internet connections
    public static boolean isConnectingToInternet() {
        Boolean result = false;
        try {
            //get the result after executing AsyncTask
            result = new GetInternetStatus().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return result;
    }
JIthin
  • 1,413
  • 1
  • 13
  • 29
0

Check Internet Connection Via - Mobile Data, Bluetooth, Wifi

  /**
 * To check internet connection
 *
 * @param context context for activity
 * @return boolean true if internet is connected else false
 */
public static boolean isInternetConnected(Context context) {
    ConnectivityManager connec = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo wifi = connec
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo mobile = connec
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    android.net.NetworkInfo bluetooth = connec
            .getNetworkInfo(ConnectivityManager.TYPE_BLUETOOTH);

    if (wifi.isConnected()) {
        return true;
    } else if (mobile.isConnected()) {
        return true;
    } else if(bluetooth.isConnected()){
        return true;
    } else if (!mobile.isConnected()) {
        return false;
    }
    return false;
}
Saravanan
  • 151
  • 2
  • 8