ndroid 监听wifi总结

功能实现:控制wifi开关,连上某个特定的wifi。


首先先上个wifi工具类,此类转载网上一人,出处不明了。 

[java]  view plain copy
  1. package rodar.rgs.conference.utils;  
  2.   
  3. import java.lang.reflect.Constructor;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.InvocationTargetException;  
  6. import java.net.InetAddress;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. import android.net.wifi.ScanResult;  
  11. import android.net.wifi.WifiConfiguration;  
  12. import android.net.wifi.WifiManager;  
  13.   
  14. public class WifiConnect {  
  15.      WifiManager wifiManager;  
  16.           
  17.     //定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况  
  18.         public enum WifiCipherType  
  19.         {  
  20.           WIFICIPHER_WEP,WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID  
  21.         }  
  22.           
  23.     //构造函数  
  24.         public WifiConnect(WifiManager wifiManager)  
  25.         {  
  26.           this.wifiManager = wifiManager;  
  27.         }  
  28.           
  29.     //打开wifi功能  
  30.          private boolean OpenWifi()  
  31.          {  
  32.              boolean bRet = true;  
  33.              if (!wifiManager.isWifiEnabled())  
  34.              {  
  35.               bRet = wifiManager.setWifiEnabled(true);    
  36.              }  
  37.              return bRet;  
  38.          }  
  39.           
  40.     //提供一个外部接口,传入要连接的无线网  
  41.          public boolean Connect(String SSID, String Password, WifiCipherType Type)  
  42.          {  
  43.             if(!this.OpenWifi())  
  44.             {  
  45.                  return false;  
  46.             }  
  47.             System.out.println(">>>wifiCon=");  
  48.     //开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi  
  49.     //状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句  
  50.             while(wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING )  
  51.             {  
  52.                  try{  
  53.          //为了避免程序一直while循环,让它睡个100毫秒在检测……  
  54.                   Thread.currentThread();  
  55.                   Thread.sleep(100);  
  56.                 }  
  57.                 catch(InterruptedException ie){  
  58.                }  
  59.             }  
  60.              
  61.         WifiConfiguration wifiConfig = this.CreateWifiInfo(SSID, Password, Type);  
  62.             //  
  63.             if(wifiConfig == null)  
  64.             {  
  65.                    return false;  
  66.             }  
  67.             WifiConfiguration tempConfig = this.IsExsits(SSID);  
  68.               
  69.             if(tempConfig != null)  
  70.             {  
  71.                 wifiManager.removeNetwork(tempConfig.networkId);  
  72.             }  
  73.               
  74. //          try {  
  75. //              //高级选项  
  76. //              String ip  ="192.168.1.201";  
  77. //              int networkPrefixLength =24;  
  78. //              InetAddress intetAddress  = InetAddress.getByName(ip);  
  79. //              int intIp = inetAddressToInt(intetAddress);    
  80. //              String dns = (intIp & 0xFF ) + "." + ((intIp >> 8 ) & 0xFF) + "." + ((intIp >> 16 ) & 0xFF) + ".1";  
  81. //              setIpAssignment("STATIC", wifiConfig); //"STATIC" or "DHCP" for dynamic setting  
  82. //              setIpAddress(intetAddress, networkPrefixLength, wifiConfig);  
  83. //              setGateway(InetAddress.getByName(dns), wifiConfig);  
  84. //              setDNS(InetAddress.getByName(dns), wifiConfig);  
  85. //          } catch (Exception e) {  
  86. //              // TODO: handle exception  
  87. //              e.printStackTrace();  
  88. //          }  
  89.               
  90.             int netID = wifiManager.addNetwork(wifiConfig);  
  91.             boolean bRet = wifiManager.enableNetwork(netID, true);   
  92. //          wifiManager.updateNetwork(wifiConfig);  
  93.               
  94.               
  95.             return bRet;  
  96.          }  
  97.            
  98.         //查看以前是否也配置过这个网络  
  99.          private WifiConfiguration IsExsits(String SSID)  
  100.          {  
  101.              List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();  
  102.                 for (WifiConfiguration existingConfig : existingConfigs)   
  103.                 {  
  104.                   if (existingConfig.SSID.equals("\""+SSID+"\""))  
  105.                   {  
  106.                       return existingConfig;  
  107.                   }  
  108.                 }  
  109.              return null;   
  110.          }  
  111.            
  112.          private WifiConfiguration CreateWifiInfo(String SSID, String Password, WifiCipherType Type)  
  113.          {  
  114.             WifiConfiguration config = new WifiConfiguration();  
  115.              config.allowedAuthAlgorithms.clear();  
  116.              config.allowedGroupCiphers.clear();  
  117.              config.allowedKeyManagement.clear();  
  118.              config.allowedPairwiseCiphers.clear();  
  119.              config.allowedProtocols.clear();  
  120.             config.SSID = "\"" + SSID + "\"";    
  121.             if(Type == WifiCipherType.WIFICIPHER_NOPASS)  
  122.             {  
  123.                  config.wepKeys[0] = "";  
  124.                  config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);  
  125.                  config.wepTxKeyIndex = 0;  
  126.             }  
  127.             if(Type == WifiCipherType.WIFICIPHER_WEP)  
  128.             {  
  129.                 config.preSharedKey = "\""+Password+"\"";   
  130.                 config.hiddenSSID = true;    
  131.                 config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);  
  132.                 config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);  
  133.                 config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);  
  134.                 config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);  
  135.                 config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);  
  136.                 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);  
  137.                 config.wepTxKeyIndex = 0;  
  138.             }  
  139.             if(Type == WifiCipherType.WIFICIPHER_WPA)  
  140.             {  
  141.             config.preSharedKey = "\""+Password+"\"";  
  142.             config.hiddenSSID = true;    
  143.             config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);    
  144.             config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);                          
  145.             config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);                          
  146.             config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);                     
  147.             //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);     
  148.             config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);   
  149.             config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);   
  150.             config.status = WifiConfiguration.Status.ENABLED;    
  151.             }  
  152.             else  
  153.             {  
  154.                 return null;  
  155.             }  
  156.             return config;  
  157.          }  
  158.            
  159.            
  160.            
  161.            
  162.            
  163.          /*** 
  164.           * Convert a IPv4 address from an InetAddress to an integer 
  165.           * @param inetAddr is an InetAddress corresponding to the IPv4 address 
  166.           * @return the IP address as an integer in network byte order 
  167.           */  
  168.          public static int inetAddressToInt(InetAddress inetAddr)  
  169.                  throws IllegalArgumentException {  
  170.              byte [] addr = inetAddr.getAddress();  
  171.              if (addr.length != 4) {  
  172.                  throw new IllegalArgumentException("Not an IPv4 address");  
  173.              }  
  174.              return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |  
  175.                      ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);  
  176.          }  
  177.            
  178.         public static void setIpAssignment(String assign, WifiConfiguration wifiConf)throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {  
  179.             setEnumField(wifiConf, assign, "ipAssignment");  
  180.         }  
  181.           
  182.         public static void setEnumField(Object obj, String value, String name) throws SecurityException, NoSuchFieldException,  
  183.         IllegalArgumentException, IllegalAccessException {  
  184.             Field f = obj.getClass().getField(name);  
  185.             f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));  
  186.         }  
  187.           
  188.         public static void setIpAddress(InetAddress addr, int prefixLength,WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,  
  189.         NoSuchFieldException,IllegalAccessException, NoSuchMethodException,ClassNotFoundException, InstantiationException,InvocationTargetException {  
  190.             Object linkProperties = getField(wifiConf, "linkProperties");  
  191.             if (linkProperties == null)  
  192.                 return;  
  193.             Class laClass = Class.forName("android.net.LinkAddress");  
  194.             Constructor laConstructor = laClass.getConstructor(new Class[] {InetAddress.classint.class });  
  195.             Object linkAddress = laConstructor.newInstance(addr, prefixLength);  
  196.             ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties,"mLinkAddresses");  
  197.             mLinkAddresses.clear();  
  198.             mLinkAddresses.add(linkAddress);  
  199.         }  
  200.   
  201.         public static void setGateway(InetAddress gateway,WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,  
  202.         NoSuchFieldException,IllegalAccessException, ClassNotFoundException,NoSuchMethodException, InstantiationException,InvocationTargetException {  
  203.             Object linkProperties = getField(wifiConf, "linkProperties");  
  204.             if (linkProperties == null)  
  205.                 return;  
  206.             Class routeInfoClass = Class.forName("android.net.RouteInfo");  
  207.             Constructor routeInfoConstructor = routeInfoClass.getConstructor(new Class[] { InetAddress.class });  
  208.             Object routeInfo = routeInfoConstructor.newInstance(gateway);  
  209.             ArrayList mRoutes = (ArrayList) getDeclaredField(linkProperties,"mRoutes");  
  210.             mRoutes.clear();  
  211.             mRoutes.add(routeInfo);  
  212.         }  
  213.   
  214.         public static void setDNS(InetAddress dns, WifiConfiguration wifiConf) throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {  
  215.             Object linkProperties = getField(wifiConf, "linkProperties");  
  216.             if (linkProperties == null)  
  217.                 return;  
  218.             ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties, "mDnses");  
  219.             mDnses.clear(); // or add a new dns address , here I just want to replace DNS1  
  220.             mDnses.add(dns);  
  221.         }  
  222.           
  223.         public static Object getField(Object obj, String name) throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {  
  224.             Field f = obj.getClass().getField(name);  
  225.             Object out = f.get(obj);  
  226.             return out;  
  227.         }  
  228.   
  229.         public static Object getDeclaredField(Object obj, String name) throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {  
  230.             Field f = obj.getClass().getDeclaredField(name);  
  231.             f.setAccessible(true);  
  232.             Object out = f.get(obj);  
  233.             return out;  
  234.         }  
  235.           
  236. //      public void editStaticWifiConfig(final ScanResult sr,String pwd, String ip, String gateway,int prefixLength,String dns) throws Exception{          
  237. //          WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);  
  238. //            
  239. //          if(historyWifiConfig == null){  
  240. //              historyWifiConfig = createComWifiConfig(sr.SSID,pwd);  
  241. //              int netId = mWifiManager.addNetwork(historyWifiConfig);  
  242. //              mWifiManager.enableNetwork(netId, true);  
  243. //          }  
  244. //            
  245. //          setIpAssignment("STATIC", historyWifiConfig); //"STATIC" or "DHCP" for dynamic setting  
  246. //          setIpAddress(InetAddress.getByName(ip), prefixLength, historyWifiConfig);  
  247. //          setGateway(InetAddress.getByName(gateway), historyWifiConfig);  
  248. //          setDNS(InetAddress.getByName(dns), historyWifiConfig);  
  249. //            
  250. //          mWifiManager.updateNetwork(historyWifiConfig); //apply the setting  
  251. //      }  
  252. //        
  253. //      public void editDhcpWifiConfig(final ScanResult sr,String pwd) throws Exception{          
  254. //          WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);  
  255. //            
  256. //          if(historyWifiConfig == null){  
  257. //              historyWifiConfig = createComWifiConfig(sr.SSID,pwd);  
  258. //              int netId = mWifiManager.addNetwork(historyWifiConfig);  
  259. //              mWifiManager.enableNetwork(netId, true);  
  260. //          }  
  261. //            
  262. //          setIpAssignment("DHCP", historyWifiConfig); //"STATIC" or "DHCP" for dynamic setting  
  263. //            
  264. //          mWifiManager.updateNetwork(historyWifiConfig); //apply the setting  
  265. //      }  
  266. }  
类中注释高级选项处,是连接上wifi同时自己设定ip.记得wifiManager.updateNetwork(wifiConfig);

类中boolean bRet = wifiManager.enableNetwork(netID, true); 第二个参数true表示如果当前已经有连上一个wifi,要强制连到自己设定的wifi上,此参数必须为true否则连上的还是原来的wifi.


调用此类示例

[java]  view plain copy
  1. WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
  2. WifiConnect wifi = new WifiConnect(wifiManager);  
  3. wifi.Connect("wifiName""wifipPassword",  
  4.         WifiCipherType.WIFICIPHER_WPA);  

需要的权限

[html]  view plain copy
  1.     <uses-permission android:name="android.permission.INTERNET" />  
  2.     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
  3.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>  
  4.       
  5.   
  6. <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />  
  7. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />  
  8. <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />  
  9. <uses-permission android:name="android.permission.WAKE_LOCK" />  

如何在广播监听wifi的状态

广播接收类

[java]  view plain copy
  1. package rodar.rgs.conference.utils;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.net.NetworkInfo;  
  7. import android.net.wifi.WifiInfo;  
  8. import android.net.wifi.WifiManager;  
  9. import android.os.Bundle;  
  10. import android.os.Parcelable;  
  11. import android.util.Log;  
  12.   
  13. public class WifiStateReceiver extends BroadcastReceiver{  
  14.   
  15. //  0 --> WIFI_STATE_DISABLING  
  16. //  1 --> WIFI_STATE_DISABLED  
  17. //  2 --> WIFI_STATE_ENABLING  
  18. //  3 --> WIFI_STATE_ENABLED  
  19. //  4 --> WIFI_STATE_UNKNOWN  
  20.       
  21.       
  22.     @Override  
  23.     public void onReceive(Context context, Intent intent) {  
  24.         // TODO Auto-generated method stub  
  25.         Bundle bundle = intent.getExtras();  
  26.           int oldInt = bundle.getInt("previous_wifi_state");  
  27.           int newInt = bundle.getInt("wifi_state");  
  28.             
  29.           System.out.println(">>>oldInt="+oldInt+",newInt="+newInt);  
  30. //        String oldStr = (oldInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[oldInt] :"?";  
  31. //        String newStr = (newInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[newInt] :"?";  
  32. //        Log.e("", "oldS="+oldStr+", newS="+newStr);  
  33. //        if(newInt==WifiManager.WIFI_STATE_DISABLED || newInt==WifiManager.WIFI_STATE_ENABLED) {  
  34. //           onWifiStateChange();  // define this function elsewhere!  
  35. //        } else if(newInt==WifiManager.WIFI_STATE_DISABLING ||  
  36. //                  newInt==WifiManager.WIFI_STATE_ENABLING)  
  37. //        {  
  38. ////           chkbox_wifi.setText(newStr);  
  39. //        } else {  
  40. //         newStr += " (Is wpa_supplicant.conf readable?)";  
  41. ////           chkbox_wifi.setText(newStr);  
  42. //        }  
  43.             
  44.         WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);  
  45.         WifiInfo info = wifiManager.getConnectionInfo();  
  46.         System.out.println(">>>onReceive.wifiInfo="+info.toString());  
  47.         System.out.println(">>>onReceive.SSID="+info.getSSID());  
  48.           
  49. //      if(!info.getSSID().equals("Rodar")){  
  50. //          WifiConnect wifi = new WifiConnect(wifiManager);  
  51. //          wifi.Connect("Rodar", "rodar.5779858",  
  52. //                  WifiCipherType.WIFICIPHER_WPA);   
  53. //          System.out.println(">>>onReceive.SSID1="+info.getSSID());  
  54. //      }  
  55.           
  56.           
  57.          if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction()))  
  58.          {  
  59.              Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);  
  60.              if (null != parcelableExtra)  
  61.              {  
  62.                  NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;  
  63.                  switch (networkInfo.getState())  
  64.                  {  
  65.                  case CONNECTED:  
  66.                      Log.e("APActivity""CONNECTED");  
  67.                      break;  
  68.                  case CONNECTING:  
  69.                      Log.e("APActivity""CONNECTING");  
  70.                      break;  
  71.                  case DISCONNECTED:  
  72.                      Log.e("APActivity""DISCONNECTED");  
  73.                      break;  
  74.                  case DISCONNECTING:  
  75.                      Log.e("APActivity""DISCONNECTING");  
  76.                      break;  
  77.                  case SUSPENDED:  
  78.                      Log.e("APActivity""SUSPENDED");  
  79.                      break;  
  80.                  case UNKNOWN:  
  81.                      Log.e("APActivity""UNKNOWN");  
  82.                      break;  
  83.                  default:  
  84.                      break;  
  85.                  }  
  86.              }  
  87.          }  
  88.   
  89.   
  90.     }  
  91.       
  92.       
  93.       
  94. //  // 显示Wifi状态以及ip地址:  
  95. //  public static String StringizeIp(int ip) {  
  96. //    int ip4 = (ip>>24) & 0x000000FF;  
  97. //    int ip3 = (ip>>16) & 0x000000FF;  
  98. //    int ip2 = (ip>> 8 )& 0x000000FF;  
  99. //    int ip1 = ip       & 0x000000FF;  
  100. //    return Integer.toString(ip1) + "." + ip2 + "." + ip3 + "." + ip4;  
  101. //  }  
  102. //  private void onWifiStateChange() {  
  103. //           String ip_str = "";  
  104. //           WifiInfo info = mMainWifi.getConnectionInfo();  
  105. //           if(info != null) {  
  106. //            int ipaddr = info.getIpAddress();  
  107. //            ip_str = " (ip="+StringizeIp(ipaddr)+")";  
  108. //           }  
  109. //            
  110. //          if(mMainWifi.isWifiEnabled()==true)  
  111. //                 chkbox_wifi.setText("Wifi is on [" + ip_str + "]");  
  112. //          else  
  113. //                 chkbox_wifi.setText("Wifi is off");  
  114. //            
  115. //  }  
  116. }  

注册和取消广播一般在onstart和onstop里

[java]  view plain copy
  1. WifiStateReceiver wifiStateReceiver;  
  2. @Override  
  3. protected void onStart() {  
  4.     //注册网络监听  
  5.     wifiStateReceiver = new WifiStateReceiver();  
  6.     IntentFilter filter = new IntentFilter();  
  7.     filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);  
  8.     filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);  
  9.     registerReceiver(wifiStateReceiver, filter);  
  10.       
  11.     super.onStart();  
  12. }  
  13.   
  14. @Override  
  15. protected void onStop() {  
  16.     //注销网络监听  
  17.     unregisterReceiver(wifiStateReceiver);  
  18.     super.onStop();  
  19. }  

你可能感兴趣的:(ndroid 监听wifi总结)