Android 检测网络类型及是否能用

Android 中网络连接检测和使用ping检测网络是否可访问
Android:检测网络状态&监听网络变化

  • 获得ConnectivityManager对象

ConnectivityManager主要用于查看网络状态和管理网络连接相关的操作

  • 获取ConnectivityManager对象对应的NetworkInfo对象

NetworkInfo对象包含网络连接的所有信息

  • 根据需要从NetworkInfo对象取出关于网络连接的信息

Android开发中网络相关的检测包括网络是否正常连接网络已连接但是否可以正常访问两类。

  • 判断网络连接类型:wifi、4g

  • 判断网络是否连接

(只能判断网络是否连接,不能判断网络是否可用)

 ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    // 获取代表联网状态的NetWorkInfo对象
    NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
    if (networkInfo == null) {
      return false;
    }
    boolean available = networkInfo.isAvailable();
    if (available) {
      Logs.i(TAG, "当前的网络连接");
    } else {
      Logs.i(TAG, "当前的网络未连接");
    }
  • 判断网络是否可用:

对于网络已连接,但是需要判断是否可以正常访问的问题,其实我们可以使用ping的方式进行检测,经过查阅网上的资料,发现好多使用 Process process=Runtime.getRuntime().exec("/system/bin/ping -c 4 "+"www.baidu.com") 进行检测的,经过测试发现会抛IOException异常,提示相关目录也就是/system/bin/ping这个找不见,主要原因是系统没有root,所以无法访问系统目录。因此这种方式肯定不是我们想要的,那么我们该如何实现呢?其实不要慌,我们可以采用如下这种方式就可以实现我们想要的效果
Process process=Runtime.getRuntime().exec("ping -c 1 -w 1 " + "www.baidu.com");

    /**
     * (1)根据DNS地址经测试这种是最方便的方式
     */
    private void dns() {
        try {
            Socket s = null;
            if (s == null) {
                s = new Socket();
            }
            InetAddress host = InetAddress.getByName("8.8.8.8");//国内使用114.114.114.114,如果全球通用google:8.8.8.8
            s.connect(new InetSocketAddress(host, 53), 5000);//google:53
            s.close();
        } catch (IOException e) {

        }

    }

  /**
     * (2)根据ping命令
     * 如果status==0则表示网络可用,其中参数-c 1是指ping的次数为1次,-w是指超时时间单位为s
     * 0 表示正常停止,即正常完成,未出现异常情况。
     * 1 表示网络已连接,但是无法访问。
     * 2 表示网络未连接。
     */
    private int ping() {
        try {
            Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 100 www.baid.com");
            int status = process.waitFor();
            return  status;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return -1;
    }
      private void ping2(String ipString) {

        Process p = null;
        try {
            p = Runtime.getRuntime().exec("ping -c 1 -w 1 " + ipString);

            // 读取ping的内容,可不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            // PING的状态
            int status = p.waitFor();
            if (status == 0) {
                sleep(3000);
            } else {
            //isEnable = false;
//            ExDispatcher.dispatchMessage(ExMessage.PING_CONNECT_BREAK);
            //interrupt();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void ping3(String address) {

        Process process = null;
        try {
            process = Runtime.getRuntime().exec("ping " + address);
   
            InputStreamReader r = new InputStreamReader(process.getInputStream());
            LineNumberReader returnData = new LineNumberReader(r);
            String returnMsg = "";
            String line = "";
            while ((line = returnData.readLine()) != null) {
                System.out.println(line);
                returnMsg += line;
            }
            if (returnMsg.indexOf("100% loss") != -1) {
                System.out.println("与 " + address + " 连接不畅通.");
            } else {
                System.out.println("与 " + address + " 连接畅通.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * (3)直接使用http连接网络,如果能成功连接则表示网络可用
     * @return
     */
    private boolean http(){
        URL url;
        try {
            url = new URL("https://www.baidu.com");
            InputStream stream = url.openStream();
            return true;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • EnglishVersion ->_->:https://github.com/jiang111/awesome-...
    聂顺阅读 1,335评论 0 4
  • 0 01、网络管理的五大功能(包括每项功能的具体情况) 1.配置管理:ISO定义的管理功能域中,配置管理包括视图管...
    哈熝少主阅读 3,700评论 1 20
  • 本文整理了在实践过程中使用的Linux网络工具,这些工具提供的功能非常强大,我们平时使用的只是冰山一角,比如lso...
    老夫刘某阅读 3,901评论 0 7
  • 姓名:于川皓 学号:16140210089 转载自:https://baike.baidu.com/item/sq...
    道无涯_cc76阅读 2,061评论 0 2
  • 1.牛掰的人都有超强的执行力 2.以“清空”的状态面对明天 3.成大事者不磨叽 4.天天想当元帅的士兵不是好士兵 ...
    不了之文阅读 270评论 0 0

友情链接更多精彩内容