How to check internet connectivity in android?

后端 未结 3 1388
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 23:44

friends,

i am trying to check internetconnectivity in android and using following code

final ConnectivityManager conn_manager = (ConnectivityManager)         


        
相关标签:
3条回答
  • 2020-12-10 00:23

    You can use requstRouteToHost to check if you can connect to a specific IP address.

    0 讨论(0)
  • 2020-12-10 00:23

    Use this nifty library: http://code.google.com/p/connectivity

    You can subscribe to network status notification and get a callback when network status changes. Or, you can query directly if network is available. Very simple to use.

    0 讨论(0)
  • 2020-12-10 00:24

    Probably some issue with the logic you have in the if clause there.

    I use this:

    /**
     * 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;
    }
    
    0 讨论(0)
提交回复
热议问题