wifi热点创建和自动连接
1.wifi热点的创建
/**
* 创建wifi热点
* @param ssid 热点信息
* @param passwd 密码
* @author wanghongbin
*/
publicvoid startWifiAp(Context context, String ssid, String passwd) {
//关闭wifi
closeWifi();
//关闭热点
closeWifiAp();
//激活热点
invokeWifiAp(ssid, passwd);
}
/**
* 激活wifi热点
* @param ssid
* @param passwd
* @author wanghongbin
*/
privatevoid invokeWifiAp(String ssid, String passwd) {
try {
Method method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",
WifiConfiguration.class, boolean.class);
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = ssid;
netConfig.preSharedKey = passwd ;
//启动热点
boolean isSuccess = (Boolean)method1.invoke(mWifiManager, netConfig, true);
Log.i(TAG, "whb end startWifiAp isSuccess="+isSuccess);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(TAG, "whb end startWifiAp IllegalArgumentException");
} catch (IllegalAcces***ception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(TAG, "whb end startWifiAp IllegalAcces***ception");
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// onNotifyWifiNotSurpport();
Log.i(TAG, "whb end startWifiAp onNotifyWifiNotSurpport");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(TAG, "whb end startWifiAp SecurityException");
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
onNotifyWifiNotSurpport();
Log.i(TAG, "whb end startWifiAp NoSuchMethodException");
}
}
// 关闭WIFI
publicvoid closeWifi() {
if (mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(false);
}
}
//作热点之前先关闭wifi热点服务
publicvoid closeWifiAp( ) {
if (isWifiApEnabled()) {
try {
Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
method.setAccessible(true);
WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);
Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method2.invoke(mWifiManager, config, false);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAcces***ception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.连接热点
/**
* 添加一个网络节点并连接
* @param ssid wifi节点名称
* @param passwd 密码
* @param type : TYPE_WEP TYPE_WPA
*/
publicvoid addNetwork(Context context, String ssid, String passwd, int type) {
closeWifiAp();
openWifi();
mConfig = createWifiInfo(ssid, passwd, type);
SSID = ssid;
connectToWifiWithConfiguration(mConfig);
}
publicstaticfinalint WAIT_FOR_SCAN_RESULT = 10 * 1000; //10 seconds
publicstaticfinalint WIFI_SCAN_TIMEOUT = 20 * 1000;
/**
* 连接指定热点
* @param config
* @return true : 调用函数成功,具体网络状态还得检测
* @author wanghongbin 这个函数害死人阿,网上看了半天也没人说,最后是看的源代码里的WifiConnectionTest.java才明白需要等待,步步等待,步步惊心
*/
publicboolean connectToWifiWithConfiguration(WifiConfiguration config) {
String ssid = config.SSID;
config.SSID = "\""+ssid+"\"";
//If Wifi is not enabled, enable it
if (!mWifiManager.isWifiEnabled()) {
Log.v(TAG, "Wifi is not enabled, enable it");
mWifiManager.setWifiEnabled(true);
}
List
netList = mWifiManager.getScanResults(); if (netList == null) {
Log.v(TAG, "scan results are null");
// if no scan results are available, start active scan
mWifiManager.startScan();
boolean mScanResultIsAvailable = false;
long startTime = System.currentTimeMillis();
while (!mScanResultIsAvailable) {
if ((System.currentTimeMillis() - startTime) > WIFI_SCAN_TIMEOUT) {
returnfalse;
}
// wait for the scan results to be available
synchronized (this) {
// wait for the scan result to be available
try {
this.wait(WAIT_FOR_SCAN_RESULT);
} catch (InterruptedException e) {
e.printStackTrace();
}
if ((mWifiManager.getScanResults() == null) ||
(mWifiManager.getScanResults().size() <= 0)) {
continue;
}
mScanResultIsAvailable = true;
}
}
}
netList = mWifiManager.getScanResults();
for (int i = 0; i < netList.size(); i++) {
ScanResult sr= netList.get(i);
if (sr.SSID.equals(ssid)) {
Log.v(TAG, "found " + ssid + " in the scan result list");
int networkId = mWifiManager.addNetwork(config);
// Connect to network by disabling others.
mWifiManager.enableNetwork(networkId, true);
mWifiManager.saveConfiguration();
mWifiManager.reconnect();
break;
}
}
List
netConfList = mWifiManager.getConfiguredNetworks(); if (netConfList.size() <= 0) {
Log.v(TAG, ssid + " is not available");
returnfalse;
}
returntrue;
}
publicstaticfinalint TYPE_NO_PASSWD = 0x11;
publicstaticfinalint TYPE_WEP = 0x12;
publicstaticfinalint TYPE_WPA = 0x13;
/**
* 连接信息生成配置对象
* @param SSID
* @param password
* @param type
* @return
* @author wanghongbin
*/
public WifiConfiguration createWifiInfo(String SSID, String password, int type) {
Log.v(TAG, "whb SSID =" + SSID + "## Password =" + password + "## Type = " + type);
WifiConfiguration config = new WifiConfiguration();
config.SSID = SSID;
clearAll(SSID);
// 分为三种情况:1没有密码2用wep加密3用wpa加密
if (type == TYPE_NO_PASSWD) {// WIFICIPHER_NOPASS
config.hiddenSSID = false;
config.status = WifiConfiguration.Status.ENABLED;
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.preSharedKey = null;
} elseif (type == TYPE_WEP) { // WIFICIPHER_WEP
config.hiddenSSID = true;
config.wepKeys[0] = "\"" + password + "\"";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
} elseif (type == TYPE_WPA) { // WIFICIPHER_WPA
config.preSharedKey = "\"" + password + "\"";
config.hiddenSSID = false;
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.priority = 10000;
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
}
return config;
}
3.很多之前已经连接上的WIFI,配置信息会自动保存,当你关闭---->打开WIFI时就会自动连接,但有时我们并不希望这样处理,解决方法为在打开WIFI之前将以前所保存的信息清除,代码为
if(isWifiConnect()){
WifiInfo info = mWifiManager.getConnectionInfo();
mWifiManager.removeNetwork(info.getNetworkId());
mWifiManager.saveConfiguration();
}
或者
/**
* 移除所有同名节点
* @param SSID
*/
privatevoid clearAll(String SSID) {
List
existingConfigs = mWifiManager.getConfiguredNetworks(); //按照networkId从大到小排序
Collections.sort(existingConfigs, new ComparatorConfig());
for (WifiConfiguration existingConfig : existingConfigs) {
LogHelper.i(TAG,"existingConfig.SSID="+existingConfig.SSID+",netID = "+ existingConfig.networkId);
if (existingConfig.SSID.equals("\""+SSID+"\"") /*&& existingConfig.preSharedKey.equals("\"" + password + "\"")*/) {
mWifiManager.disableNetwork(existingConfig.networkId);
mWifiManager.removeNetwork(existingConfig.networkId);
}
}
mWifiManager.saveConfiguration();
}