Android wifi热点创建和自动连接

                   

       wifi热点创建和自动连接        

       分类:            Android 226人阅读 评论(0) 收藏 举报
[java] view plain copy
  1. 1.wifi热点的创建  

  2. /**

  3.  * 创建wifi热点

  4.  * @param ssid 热点信息

  5.  * @param passwd  密码

  6.  * @author wanghongbin

  7.  */

  8. publicvoid startWifiAp(Context context, String ssid, String passwd) {  

  9. //关闭wifi

  10. closeWifi();  

  11. //关闭热点

  12. closeWifiAp();  

  13. //激活热点

  14. invokeWifiAp(ssid, passwd);  

  15. }  

  16. /**

  17.  * 激活wifi热点

  18.  * @param ssid

  19.  * @param passwd

  20.  * @author wanghongbin

  21.  */

  22. privatevoid invokeWifiAp(String ssid, String passwd) {  

  23. try {  

  24. Method method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",  

  25. WifiConfiguration.class, boolean.class);  

  26. WifiConfiguration netConfig = new WifiConfiguration();  

  27. netConfig.SSID = ssid;  

  28. netConfig.preSharedKey =   passwd ;  

  29. //启动热点

  30. boolean isSuccess = (Boolean)method1.invoke(mWifiManager, netConfig, true);  

  31. Log.i(TAG, "whb end startWifiAp isSuccess="+isSuccess);  

  32. } catch (IllegalArgumentException e) {  

  33. // TODO Auto-generated catch block

  34. e.printStackTrace();  

  35. Log.i(TAG, "whb end startWifiAp IllegalArgumentException");  

  36. } catch (IllegalAcces***ception e) {  

  37. // TODO Auto-generated catch block

  38. e.printStackTrace();  

  39. Log.i(TAG, "whb end startWifiAp IllegalAcces***ception");  

  40. } catch (InvocationTargetException e) {  

  41. // TODO Auto-generated catch block

  42. e.printStackTrace();  

  43. // onNotifyWifiNotSurpport();

  44. Log.i(TAG, "whb end startWifiAp onNotifyWifiNotSurpport");  

  45. } catch (SecurityException e) {  

  46. // TODO Auto-generated catch block

  47. e.printStackTrace();  

  48. Log.i(TAG, "whb end startWifiAp SecurityException");  

  49. } catch (NoSuchMethodException e) {  

  50. // TODO Auto-generated catch block

  51. e.printStackTrace();  

  52.  onNotifyWifiNotSurpport();  

  53.  Log.i(TAG, "whb end startWifiAp NoSuchMethodException");  

  54. }  

  55. }  

  56. // 关闭WIFI

  57. publicvoid closeWifi() {  

  58. if (mWifiManager.isWifiEnabled()) {  

  59. mWifiManager.setWifiEnabled(false);  

  60. }  

  61. }  

  62. //作热点之前先关闭wifi热点服务

  63. publicvoid closeWifiAp( ) {  

  64. if (isWifiApEnabled()) {  

  65. try {  

  66. Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");  

  67. method.setAccessible(true);  

  68. WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);  

  69. Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);  

  70. method2.invoke(mWifiManager, config, false);  

  71. } catch (NoSuchMethodException e) {  

  72. // TODO Auto-generated catch block

  73. e.printStackTrace();  

  74. } catch (IllegalArgumentException e) {  

  75. // TODO Auto-generated catch block

  76. e.printStackTrace();  

  77. } catch (IllegalAcces***ception e) {  

  78. // TODO Auto-generated catch block

  79. e.printStackTrace();  

  80. } catch (InvocationTargetException e) {  

  81. // TODO Auto-generated catch block

  82. e.printStackTrace();  

  83. }  

  84. }  

  85. }  

  86. 2.连接热点  

  87. /**

  88.  * 添加一个网络节点并连接

  89.  * @param ssid   wifi节点名称

  90.  * @param passwd  密码

  91.  * @param type  : TYPE_WEP TYPE_WPA

  92.  */

  93. publicvoid addNetwork(Context context, String ssid, String passwd, int type) {  

  94. closeWifiAp();  

  95. openWifi();  

  96. mConfig = createWifiInfo(ssid, passwd, type);  

  97. SSID = ssid;  

  98. connectToWifiWithConfiguration(mConfig);  

  99. }  

  100. publicstaticfinalint WAIT_FOR_SCAN_RESULT = 10 * 1000; //10 seconds

  101. publicstaticfinalint WIFI_SCAN_TIMEOUT = 20 * 1000;  

  102. /**

  103.      * 连接指定热点

  104.      * @param config

  105.      * @return true : 调用函数成功,具体网络状态还得检测

  106.      * @author wanghongbin  这个函数害死人阿,网上看了半天也没人说,最后是看的源代码里的WifiConnectionTest.java才明白需要等待,步步等待,步步惊心

  107.      */

  108. publicboolean connectToWifiWithConfiguration(WifiConfiguration config) {  

  109.         String ssid = config.SSID;  

  110.         config.SSID = "\""+ssid+"\"";  

  111. //If Wifi is not enabled, enable it

  112. if (!mWifiManager.isWifiEnabled()) {  

  113.             Log.v(TAG, "Wifi is not enabled, enable it");  

  114.             mWifiManager.setWifiEnabled(true);  

  115.         }  

  116.         List<ScanResult> netList = mWifiManager.getScanResults();  

  117. if (netList == null) {  

  118.             Log.v(TAG, "scan results are null");  

  119. // if no scan results are available, start active scan

  120.             mWifiManager.startScan();  

  121. boolean mScanResultIsAvailable = false;  

  122. long startTime = System.currentTimeMillis();  

  123. while (!mScanResultIsAvailable) {  

  124. if ((System.currentTimeMillis() - startTime) > WIFI_SCAN_TIMEOUT) {  

  125. returnfalse;  

  126.                 }  

  127. // wait for the scan results to be available

  128. synchronized (this) {  

  129. // wait for the scan result to be available

  130. try {  

  131. this.wait(WAIT_FOR_SCAN_RESULT);  

  132.                     } catch (InterruptedException e) {  

  133.                         e.printStackTrace();  

  134.                     }  

  135. if ((mWifiManager.getScanResults() == null) ||  

  136.                             (mWifiManager.getScanResults().size() <= 0)) {  

  137. continue;  

  138.                     }  

  139.                     mScanResultIsAvailable = true;  

  140.                 }  

  141.             }  

  142.         }  

  143.         netList = mWifiManager.getScanResults();  

  144. for (int i = 0; i < netList.size(); i++) {  

  145.             ScanResult sr= netList.get(i);  

  146. if (sr.SSID.equals(ssid)) {  

  147.                 Log.v(TAG, "found " + ssid + " in the scan result list");  

  148. int networkId = mWifiManager.addNetwork(config);  

  149. // Connect to network by disabling others.

  150.                 mWifiManager.enableNetwork(networkId, true);  

  151.                 mWifiManager.saveConfiguration();  

  152.                 mWifiManager.reconnect();  

  153. break;  

  154.            }  

  155.         }  

  156.         List<WifiConfiguration> netConfList = mWifiManager.getConfiguredNetworks();  

  157. if (netConfList.size() <= 0) {  

  158.             Log.v(TAG, ssid + " is not available");  

  159. returnfalse;  

  160.         }  

  161. returntrue;  

  162.     }  

  163. publicstaticfinalint TYPE_NO_PASSWD = 0x11;  

  164. publicstaticfinalint TYPE_WEP = 0x12;  

  165. publicstaticfinalint TYPE_WPA = 0x13;  

  166. /**

  167.  * 连接信息生成配置对象

  168.  * @param SSID

  169.  * @param password

  170.  * @param type

  171.  * @return

  172.  * @author wanghongbin

  173.  */

  174. public WifiConfiguration createWifiInfo(String SSID, String password, int type) {  

  175. Log.v(TAG, "whb SSID =" + SSID + "## Password =" + password + "## Type = " + type);  

  176.       WifiConfiguration config = new WifiConfiguration();  

  177.        config.SSID = SSID;        

  178.        clearAll(SSID);  

  179. // 分为三种情况:1没有密码2用wep加密3用wpa加密

  180. if (type == TYPE_NO_PASSWD) {// WIFICIPHER_NOPASS

  181.            config.hiddenSSID = false;  

  182.            config.status =  WifiConfiguration.Status.ENABLED;  

  183.            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);  

  184.            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);  

  185.            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);  

  186.            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);  

  187.            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);  

  188.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);  

  189.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);  

  190.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);  

  191.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);  

  192.            config.preSharedKey = null;  

  193.        } elseif (type == TYPE_WEP) { // WIFICIPHER_WEP

  194.            config.hiddenSSID = true;  

  195.            config.wepKeys[0] = "\"" + password + "\"";  

  196.            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);  

  197.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);  

  198.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);  

  199.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);  

  200.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);  

  201.            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);  

  202.            config.wepTxKeyIndex = 0;  

  203.        } elseif (type == TYPE_WPA) { // WIFICIPHER_WPA

  204.            config.preSharedKey = "\"" + password + "\"";  

  205.            config.hiddenSSID = false;  

  206.            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);  

  207.            config.priority = 10000;  

  208.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);  

  209.            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);  

  210.            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);  

  211.            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);  

  212.            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);  

  213.            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);  

  214.            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);  

  215.            config.status = WifiConfiguration.Status.ENABLED;  

  216.        }  

  217. return config;  

  218. }  

  219. 3.很多之前已经连接上的WIFI,配置信息会自动保存,当你关闭---->打开WIFI时就会自动连接,但有时我们并不希望这样处理,解决方法为在打开WIFI之前将以前所保存的信息清除,代码为  

  220. if(isWifiConnect()){  

  221.    WifiInfo info = mWifiManager.getConnectionInfo();  

  222.    mWifiManager.removeNetwork(info.getNetworkId());  

  223.    mWifiManager.saveConfiguration();  

  224.   }  

  225.  或者  

  226. /**

  227.  * 移除所有同名节点

  228.  * @param SSID

  229.  */

  230. privatevoid clearAll(String SSID) {  

  231. List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();  

  232. //按照networkId从大到小排序

  233. Collections.sort(existingConfigs, new ComparatorConfig());  

  234. for (WifiConfiguration existingConfig : existingConfigs) {  

  235. LogHelper.i(TAG,"existingConfig.SSID="+existingConfig.SSID+",netID = "+ existingConfig.networkId);  

  236. if (existingConfig.SSID.equals("\""+SSID+"\"") /*&& existingConfig.preSharedKey.equals("\"" + password + "\"")*/) {  

  237. mWifiManager.disableNetwork(existingConfig.networkId);  

  238. mWifiManager.removeNetwork(existingConfig.networkId);  

  239. }  

  240. }  

  241. mWifiManager.saveConfiguration();  

  242. }  


你可能感兴趣的:(android,wifi)