how to check wifi or 3g network is available on android device

前端 未结 4 1241
说谎
说谎 2020-11-27 02:59

Here, my android device supports both wifi and 3g. At particular time which network is available on this device. Because my requirement is when 3g is available I have to upl

4条回答
  •  醉酒成梦
    2020-11-27 03:40

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

    You also need

    
    

    in AndroidMainfest.xml

    To get the network type you can use this code snippet:

    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
    //mobile
    State mobile = conMan.getNetworkInfo(0).getState();
    
    //wifi
    State wifi = conMan.getNetworkInfo(1).getState();
    

    and then use it like that:

    if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
        //mobile
    } else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
        //wifi
    }
    

    To get the type of the mobile network I would try TelephonyManager#getNetworkType or NetworkInfo#getSubtypeName

提交回复
热议问题