androidandroid-studioandroid-wifiandroid-internet

How I can check android device is connected to the Internet?


Is there any way to find out that android device is connected to the Internet or not. I use this function:

    public boolean isDeviceOnline() {     
        ConnectivityManager cm =
        (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();     
        return netInfo != null && netInfo.isConnectedOrConnecting(); 
    }

but this function return true if device connected to a WiFi network that doesn't include internet access or requires browser-based authentication and I want return false in this situation.


Solution

  • try this

    public class ConnectionDetector {
    
    private Context _context;
    
    public ConnectionDetector(Context context) {
        this._context = context;
    }
    
    public boolean isInternetAvailble() {
        return isConnectingToInternet() || isConnectingToWifi();
    }
    
    private boolean isConnectingToInternet() {
        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) {
                        return true;
                    }
    
        }
        return false;
    }
    
    private boolean isConnectingToWifi() {
        ConnectivityManager connManager = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWifi != null) {
            if (mWifi.getState() == NetworkInfo.State.CONNECTED)
                return true;
        }
        return false;
    } }
    

    declare like this

    ConnectionDetector ConnectionDetector = new ConnectionDetector(
                context.getApplicationContext());
    

    use like is

    ConnectionDetector.isInternetAvailble()