Android 判断是否能真正上网的实例详解

2020-10-22 09:55:18 浏览数 (1)

Android 判断是否能真正上网的实例详解

检测网络是否连接

实现代码:

代码语言:javascript复制
/**

 *
 检测网络是否连接

 *

 *
 @return

 */

private

boolean 
isNetworkAvailable() {

  //
 得到网络连接信息

  ConnectivityManager
 manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

  //
 去进行判断网络是否连接

  if

(manager.getActiveNetworkInfo() != null)
 {

    return

manager.getActiveNetworkInfo().isAvailable();

  }

  return

false;

}

ping的状态

代码语言:javascript复制
public static final boolean ping() {

  String result = null;
  try {
    String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
    Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 "   ip);// ping网址3次
    // 读取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);
    }
    Log.d("------ping-----", "result content : "   stringBuffer.toString());
    // ping的状态
    int status = p.waitFor();
    if (status == 0) {
      result = "success";
      return true;
    } else {
      result = "failed";
    }
  } catch (IOException e) {
    result = "IOException";
  } catch (InterruptedException e) {
    result = "InterruptedException";
  } finally {
    Log.d("----result---", "result = "   result);
  }
  return false;

}

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

0 人点赞