The perfect function to check Android internet connectivity including bluetooth pan

自作多情 提交于 2019-11-29 11:55:43

问题


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..


回答1:


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;
}



回答2:


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;
            }



回答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.




回答4:


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




回答5:


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" />



回答6:


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;
    }



回答7:


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;
}


来源:https://stackoverflow.com/questions/28059519/the-perfect-function-to-check-android-internet-connectivity-including-bluetooth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!