[Java] Android系统下检测Wifi连接互联网是否正常的代码 →→→→→进入此内容的聊天室

来自 , 2020-07-10, 写在 Java, 查看 118 次.
URL http://www.code666.cn/view/4ccea316
  1. /**
  2.  *
  3.  * 判断网络状态是否可用
  4.  *
  5.  * @return true: 网络可用 ; false: 网络不可用
  6.  */
  7.  
  8. public boolean isConnectInternet()
  9. {
  10.     ConnectivityManager conManager = (ConnectivityManager) test.this
  11.             .getSystemService(Context.CONNECTIVITY_SERVICE);
  12.     NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
  13.     if (networkInfo == null || !networkInfo.isConnected())
  14.     {
  15.         return false;
  16.     }
  17.     if (networkInfo.isConnected())
  18.     {
  19.         return true;
  20.     }
  21.     return false;
  22. }
  23. /* 检查网络联机是否正常 */
  24. public boolean checkInternetConnection(String strURL, String strEncoding)
  25. {
  26.     /* 最多延时n秒若无响应则表示无法联机 */
  27.     int intTimeout = 10;
  28.     try
  29.     {
  30.         HttpURLConnection urlConnection = null;
  31.         URL url = new URL(strURL);
  32.         urlConnection = (HttpURLConnection) url.openConnection();
  33.         urlConnection.setRequestMethod("GET");
  34.         urlConnection.setDoOutput(true);
  35.         urlConnection.setDoInput(true);
  36.         urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0"
  37.                 + " (compatible; MSIE 6.0; Windows 2000)");
  38.  
  39.         urlConnection.setRequestProperty("Content-type",
  40.                 "text/html; charset=" + strEncoding);
  41.         urlConnection.setConnectTimeout(1000 * intTimeout);
  42.         urlConnection.connect();
  43.         if (urlConnection.getResponseCode() == 200)
  44.         {
  45.             return true;
  46.         }
  47.         else
  48.         {
  49.             Log.d("getResponseCode=", urlConnection.getResponseMessage());
  50.  
  51.             return false;
  52.         }
  53.     }
  54.     catch (Exception e)
  55.     {
  56.         e.printStackTrace();
  57.         Log.d("emessage", e.getMessage());
  58.         return false;
  59.     }
  60. }
  61.  
  62. /* 自定义BIG5转UTF-8 */
  63. public String big52unicode(String strBIG5)
  64. {
  65.     String strReturn = "";
  66.     try
  67.     {
  68.         strReturn = new String(strBIG5.getBytes("big5"), "UTF-8");
  69.     }
  70.     catch (Exception e)
  71.     {
  72.         e.printStackTrace();
  73.     }
  74.     return strReturn;
  75. }
  76.  
  77. /* 自定义UTF-8转BIG5 */
  78. public String unicode2big5(String strUTF8)
  79. {
  80.     String strReturn = "";
  81.     try
  82.     {
  83.         strReturn = new String(strUTF8.getBytes("UTF-8"), "big5");
  84.     }
  85.     catch (Exception e)
  86.     {
  87.         e.printStackTrace();
  88.     }
  89.     return strReturn;
  90. }
  91. //java/6854

回复 "Android系统下检测Wifi连接互联网是否正常的代码"

这儿你可以回复上面这条便签

captcha