使用场景
最近用了手机QQ的面对面快传来传相片给朋友,非常方便。但这个功能只能单个传输,如果想一次性传给多个朋友,无法做到。所以,试下自己做这个功能,首先,从创建Wi-Fi热点和连接Wi-Fi开始。代码示例:创建Wi-Fi热点
/**
* 设置Wi-Fi热点配置信息
*
* @param SSID
* @param pwd
* @param keyMgmt
* @return
*/
public WifiConfiguration setWifiConfig(String SSID, String pwd, int keyMgmt) {
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = SSID;
switch (keyMgmt) {
case NONE:
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
break;
case WPA2_PSK:
wifiConfiguration.preSharedKey = pwd;
//WPA2_PSK = 4,在KeyMgmt中被隐藏,设置4即可开启WPA2热点
wifiConfiguration.allowedKeyManagement.set(WPA2_PSK);
break;
}
return wifiConfiguration;
}
/**
* 开启Wi-Fi热点
* * @param wifiConfiguration Wi-Fi配置信息
*/
public boolean openWifiAp(WifiConfiguration wifiConfiguration) {
if (wifiConfiguration == null) {
return false;
}
Method method = null;
try {
closeWifi();
//使用反射开启Wi-Fi热点
method = mWifiManager.getClass().getMethod("setWifiApEnabled", wifiConfiguration.getClass(), boolean.class);
method.invoke(mWifiManager, wifiConfiguration, true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
return false;
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
}
return true;
}
说明
这里创建的是WPA2类型的Wi-Fi热点,并且热点可设置密码。主要还是WifiConfiguration向开发者隐藏了WPA2_PSK,而这个变量值为4,所以设置下keyMgmt为4就可以了。连接指定Wi-Fi
/**
* 添加一个网络并连接
*
* @param wcg
* @return
*/
public boolean addNetwork(WifiConfiguration wcg) {
int wcgID = mWifiManager.addNetwork(wcg);
return mWifiManager.enableNetwork(wcgID, true);
}
/**
* 连接一个Wi-Fi热点
*
* @param SSID
* @param pwd
* @return
*/
public boolean connectWifi(String SSID, String pwd) {
WifiConfiguration config = null;
if (isEmpty(SSID)) {
return false;
}
openWifi();
if (isEmpty(pwd)) {
config = setWifiConfig(SSID, pwd, NONE);
} else {
config = setWifiConfig(SSID, pwd, WPA2_PSK);
}
return addNetwork(config);
}
接下来,会继续做文件传输这个模块。