判断当前网络是否可用两种方法

1,828 阅读1分钟

public class NetUtils {

public static final int NETWORK_CONNECTED = 0;
public static final int NETWORK_LOADING_USE = 1;
public static final int NETWORK_DISCONNECTED = 2;
public static final int NETWORK_ERROR = 1000;


/**
 * 判断当前网络是否可用(通用方法)
 * 耗时12秒
 * @return
 */
public static boolean isNetPingUsable(){
    Runtime runtime = Runtime.getRuntime();
    try {
        Process process = runtime.exec("ping -c 3 www.baidu.com");
        int ret = process.waitFor();
        if (ret == NETWORK_CONNECTED){
            return true;
        }else {
            return false;
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return false;
}


/**
 * 判断当前网络是否可用(6.0以上版本(M)(21))
 * 实时
 * @param context
 * @return
 */
public static boolean isNetSystemUsable(Context context){
    boolean isNetUsable = false;
    ConnectivityManager manager = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        NetworkCapabilities networkCapabilities =
                manager.getNetworkCapabilities(manager.getActiveNetwork());
        isNetUsable = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
    }
    return isNetUsable;
}


/**
 *  获取当前网络状态
 *  0:当前网络可用
 *  1:需要网页认证的wifi
 *  2:网络不可用的状态
 *  1000:方法错误
 *
 * @return
 */
public static int netPingAction(){
    Runtime runtime = Runtime.getRuntime();
    try {
        Process process = runtime.exec("ping -c 3 www.baidu.com");
        int ret = process.waitFor();
        return ret;
    }catch (Exception e){
        e.printStackTrace();
    }
    return NETWORK_ERROR;
}

/** * 通过socket检查外网的连通性 */

private static Socket s ;

public static boolean hasNetworkConnection(Context context){
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    
    boolean connected = (null != activeNetworkInfo) && activeNetworkInfo.isConnected();
    if(!connected) return false;
    boolean routeExists ;
    try {
        if(s==null){
            s = new Socket();
        }
        InetAddress host = InetAddress.getByName("114.114.114.114");//国内使用114.114.114.114,如果全球通用google:8.8.8.8
        s.connect(new InetSocketAddress(host,80),5000);//google:53
        routeExists = true;
        s.close();
    } catch (IOException e) {
        routeExists = false ;
    }

    return connected && routeExists ;
}

}