Check internet in android emulator

I am trying to test internet connection in my android app.

    public static boolean isConnectingToInternet(Context _context) {
    ConnectivityManager connectivity = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    Log.d("Network",
                            "NETWORKnAME: " + info[i].getTypeName());
                    return true;
                }

    }
    return false;
}

      

but the problem is when I try to test the internet connection in the emulator by disconnecting the internet connection of the host machine, this function returns true that there is internet, while I disconnect the internet connection from the host machine

 ConnectivityManager

help in determining if network with network not about internet connection

My question is how to check if the internet connection is not available?

+3


source to share


2 answers


Try turning off Wi-Fi and data packet again. Hope this helps.



0


source


Try this to detect your internet connection.

public static boolean isInternetConnected(Context mContext) {

            try {
                ConnectivityManager connect = null;
                connect = (ConnectivityManager) mContext
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                if (connect != null) {
                    NetworkInfo resultMobile = connect
                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                    NetworkInfo resultWifi = connect
                            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                    if ((resultMobile != null && resultMobile
                            .isConnectedOrConnecting())
                            || (resultWifi != null && resultWifi
                                    .isConnectedOrConnecting())) {
                        return true;
                    } else {
                        return false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return false;
        }

      



Add the following permissions to your manifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

      

-2


source







All Articles