软件测试布道师的江湖

深耕软件测试领域,定期分享技术干货,一起成长!

Android检测wifi网络的连接情况

 1 public static boolean isWifiConnected(Context context)
 2 {
 3     ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
 4     NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
 5     if(wifiNetworkInfo.isConnected())
 6     {
 7         return true ;
 8     }
 9  
10     return false ;
11 }
ConnectivityManager 类中封装了和链接相关的(Wi-Fi, GPRS, UMTS, etc)相关的方法和类,能够检测当前的连接状态。

1  WifiManager wifiMgr = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
2     int state = wifiMgr.getWifiState();
3     if (state == WifiManager.WIFI_STATE_ENABLED || state == WifiManager.WIFI_STATE_ENABLING) {
4     return true;
5     } else {
6     return false;
7     }
This class provides the primary API for managing all aspects of Wi-Fi connectivity. Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE). It deals with several categories of items:

The list of configured networks. The list can be viewed and updated, and attributes of individual entries can be modified.
The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
Results of access point scans, containing enough information to make decisions about what access point to connect to.
It defines the names of various Intent actions that are broadcast upon any sort of change in Wi-Fi state.
This is the API to use when performing Wi-Fi specific operations. To perform operations that pertain to network connectivity at an abstract level, use android.net.ConnectivityManager.

总之  ConnectivityManager主要管理和网络连接相关的操作,而WifiManager主要管理和Wifi相关的操作。

posted @ 2012-11-10 14:54  布道师玄柯  阅读(1273)  评论(0编辑  收藏  举报