判断当前网络连接类型

作者:追风剑情 发布于:2015-12-24 15:45 分类:Android

  1. public void onClick(View view)
  2. {
  3. TextView textView = (TextView) findViewById(R.id.infoText);
  4. ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);
  5. NetworkInfo activeNetInfo = con.getActiveNetworkInfo();//获取网络的连接情况
  6. if(null == activeNetInfo)
  7. {
  8. textView.setText("NetworkInfo: NULL, 无网络连接");
  9. return;
  10. }
  11. if(!activeNetInfo.isAvailable()){
  12. textView.setText("网络无效");
  13. return;
  14. }
  15.  
  16. State state = activeNetInfo.getState();
  17. if(state.equals(State.DISCONNECTED)){
  18. textView.setText("网络已断开");
  19. return;
  20. }
  21. if(state.equals(State.DISCONNECTED)){
  22. textView.setText("网络正在断开...");
  23. return;
  24. }
  25. if(state.equals(State.CONNECTING)){
  26. textView.setText("网络连接中...");
  27. return;
  28. }
  29. String info = "";
  30. if(state.equals(State.CONNECTED)){
  31. info += "网络已连接上\n";
  32. }
  33. int netType = activeNetInfo.getType();
  34. info += "网络类型: "+netType+", "+activeNetInfo.getTypeName() + "\n";
  35. info += "详细信息:\n" + activeNetInfo.toString();
  36. textView.setText(info);
  37. }

 

需要添加以下权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

 

运行效果

11.png

 

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号