如何在Android中检查互联网连接?

UMA*_*MAR 4 android

朋友们,

我正在尝试检查android中的internetconnectivity并使用以下代码

final ConnectivityManager conn_manager = (ConnectivityManager) 
            this.getSystemService(Context.CONNECTIVITY_SERVICE);


            final NetworkInfo network_info = conn_manager.getActiveNetworkInfo();
            if ( network_info != null && network_info.isConnected() ) 
            {
                return true;
            }
            else
            {
                return false;
            }
Run Code Online (Sandbox Code Playgroud)

但它给了我网络/ wifi连接,如果wifi连接它给我真实,如果互联网没有连接,那么它也给了我真实.

任何一个人指导我的解决方案是什么?

Pen*_*m10 12

可能是你在if那里的条款中存在的逻辑问题.

我用这个:

/**
 * Checks if we have a valid Internet Connection on the device.
 * @param ctx
 * @return True if device has internet
 *
 * Code from: http://www.androidsnippets.org/snippets/131/
 */
public static boolean haveInternet(Context ctx) {

    NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        return false;
    }
    if (info.isRoaming()) {
        // here is the roaming option you can change it if you want to
        // disable internet while roaming, just return false
        return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)