简体   繁体   中英

Android network checking is not working in some devices

Hello I am new in android ,I implemented a method to check internet connection.It works fine in some devices and not working in samsung galaxy tab 4. I searched a lot and didin't find a solution.My device can connect internet from other apps.It works fine in all other devices. Please help me thanks in advance

public boolean isConnected() {
        try {

            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm.getActiveNetworkInfo() != null
                    && cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
                // Network is available but check if we can get access from the
                // network.
                URL url = new URL("http://www.google.co.in");
                HttpURLConnection urlc = (HttpURLConnection) url
                        .openConnection();
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(2000); // Timeout 2 seconds.
                urlc.connect();

                if (urlc.getResponseCode() == 200) // Successful response.
                {
                    Log.d("response", "" + urlc.getResponseCode());
                    return true;
                } else {

                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }  

Try:

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnected();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM