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

笑着哭i 提交于 2019-12-08 10:10:41

问题


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.


回答1:


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()



回答2:


just try this method >

public boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null; // return true =(connected),false=(not connected)
}



回答3:


Change this:

return netInfo != null && netInfo.isConnectedOrConnecting();

To:

return netInfo != null && netInfo.isConnected();

Then call it like

if(!isDeviceOnline()) {
    System.out.println("Not connected");
}


来源:https://stackoverflow.com/questions/45797996/how-i-can-check-android-device-is-connected-to-the-internet

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