如何在android中连接wifi网络检查Internet是否处于活动状态

时间:2012-09-03 00:44:07

标签: android wifi

如何在Android中连接的WiFi网络上自动检查互联网是否处于活动状态?我可以检查wifi是否已启用或是否已连接wifi网络但我不确定如何检查互联网是否已连接?这可能吗?

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;
}

上面检查wifi启用/ wifi连接与否但不上网。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

如果您想检查您的设备是否已连接wifi,请使用此方法。

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

如果您想检查您的设备是否已连接到移动网络互联网,请使用此方法。

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;
    }

注意:不要忘记添加权限

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