android – 检测如果没有互联网连接

前端之家收集整理的这篇文章主要介绍了android – 检测如果没有互联网连接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个代码来确定是否有网络连接:

  1. ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  2. NetworkInfo netInfo = cm.getActiveNetworkInfo();
  3. if (netInfo != null && netInfo.isConnected())
  4. {
  5. // There is an internet connection
  6. }

但如果有网络连接而没有互联网,这是没用的.我必须ping一个网站并等待响应或超时以确定互联网连接:

  1. URL sourceUrl;
  2. try {
  3. sourceUrl = new URL("http://www.google.com");
  4. URLConnection Connection = sourceUrl.openConnection();
  5. Connection.setConnectTimeout(500);
  6. Connection.connect();
  7. } catch (MalformedURLException e) {
  8. // TODO Auto-generated catch block
  9. e.printStackTrace();
  10. // no Internet
  11. } catch (IOException e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. // no Internet
  15. }

但这是一个缓慢的检测.我应该学习一种快速方法来检测它.

提前致谢.

最佳答案
尝试以下方法来检测不同类型的连接:

  1. private boolean haveNetworkConnection(Context context)
  2. {
  3. boolean haveConnectedWifi = false;
  4. boolean haveConnectedMobile = false;
  5. ConnectivityManager cm = (ConnectivityManager) Your_Activity_Name.this.getSystemService(Context.CONNECTIVITY_SERVICE);
  6. // or if function is out side of your Activity then you need context of your Activity
  7. // and code will be as following
  8. // (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  9. NetworkInfo[] netInfo = cm.getAllNetworkInfo();
  10. for (NetworkInfo ni : netInfo)
  11. {
  12. if (ni.getTypeName().equalsIgnoreCase("WIFI"))
  13. {
  14. if (ni.isConnected())
  15. {
  16. haveConnectedWifi = true;
  17. System.out.println("WIFI CONNECTION AVAILABLE");
  18. } else
  19. {
  20. System.out.println("WIFI CONNECTION NOT AVAILABLE");
  21. }
  22. }
  23. if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
  24. {
  25. if (ni.isConnected())
  26. {
  27. haveConnectedMobile = true;
  28. System.out.println("MOBILE INTERNET CONNECTION AVAILABLE");
  29. } else
  30. {
  31. System.out.println("MOBILE INTERNET CONNECTION NOT AVAILABLE");
  32. }
  33. }
  34. }
  35. return haveConnectedWifi || haveConnectedMobile;
  36. }

猜你在找的Android相关文章