How to check if Internet is active with wifi network connected in android

泄露秘密 提交于 2019-12-14 01:52:51

问题


How to check automatically if internet is active on the WiFi network connected in android? I can check if wifi is enabled or if wifi network is connected but I am not sure how to check if internet is connected? Is this possible?

private boolean connectionAvailable() 
{
    boolean connected = false;
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
        //we are connected to a network
        connected = true;
    }
    return connected;
}

Above checks on wifi enabled/wifi connected or not but not internet.


回答1:


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



回答2:


If you want to check your device is connected with wifi then use this method.

    public static boolean isInternetConnected(Context context) {
    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mnetwork = connManager.getActiveNetworkInfo();
    return mnetwork != null && mnetwork.isConnected();
}

And if you want to check your device is connected with Mobile Network Internet then use this method.

public static boolean isMobileInternetConnected(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetwork = connManager.getActiveNetworkInfo();
        return mNetwork != null && mNetwork.isConnected() && mNetwork.getType() == ConnectivityManager.TYPE_MOBILE;
    }

Note: Don't Forget to Add Permission

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


来源:https://stackoverflow.com/questions/12240867/how-to-check-if-internet-is-active-with-wifi-network-connected-in-android

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