2

如何在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 连接但不是互联网。

4

2 回答 2

2
public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}
于 2012-09-03T00:48:12.670 回答
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" />
于 2017-02-08T07:17:45.833 回答