版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40391500/article/details/82350687
设置静态IP需要先忘记WiFi密码再重新连接,会记住是哪个APP连接WiFi
public class WifiConnet {
private static WifiConnet utils = null;
private WifiManager wifiManager;
public static int Num = 0;
public static String SSID = "";
// 构造函数
public static synchronized WifiConnet getIntance() {
if (utils == null){
utils = new WifiConnector();
}
return utils;
}
public void initWifi(WifiManager wifiManager, String ssid, String password, WifiCipherType type,
String ipAddress, String gateway, String dns, ProgressDialogUtil progress){
LogUtils.printLog("开始连接WiFi");
this.SSID = ssid;
this.wifiManager = wifiManager;
try {
removeWifiBySsid(wifiManager);
Thread.sleep(500);
connect(ssid, password, type, ipAddress, gateway, dns, progress);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 忘记某一个wifi密码
*
* @param wifiManager
*/
public static void removeWifiBySsid(WifiManager wifiManager) {
List<WifiConfiguration> wifiConfigs = wifiManager.getConfiguredNetworks();
if (wifiConfigs != null){
for (WifiConfiguration wifiConfig : wifiConfigs) {
// LogUtils.printLog("移除WiFi", wifiConfig.SSID);
if (wifiConfig != null){
wifiManager.disableNetwork(wifiConfig.networkId);
wifiManager.disconnect();
wifiManager.removeNetwork(wifiConfig.networkId);
wifiManager.saveConfiguration();
}
}
}
}
//WIFICIPHER_WEP是WEP ,WIFICIPHER_WPA是WPA,WIFICIPHER_NOPASS没有密码
public enum WifiCipherType {
WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
}
Thread thread = null;
// 提供一个外部接口,传入要连接的无线网
public void connect(String ssid, String password, WifiCipherType type,
String ipAddress, String gateway, String dns, ProgressDialogUtil progress) {
thread = new Thread(new ConnectRunnable(ssid, password, type, ipAddress, gateway, dns, progress));
thread.start();
}
// 查看以前是否也配置过这个网络
private WifiConfiguration isExsits(String SSID) {
List<WifiConfiguration> existingConfigs = wifiManager
.getConfiguredNetworks();
if (existingConfigs != null){
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
}
return null;
}
private WifiConfiguration createWifiInfo(String SSID, String Password,
WifiCipherType Type) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
// nopass
if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
// wep
if (Type == WifiCipherType.WIFICIPHER_WEP) {
if (!TextUtils.isEmpty(Password)) {
if (isHexWepKey(Password)) {
config.wepKeys[0] = Password;
} else {
config.wepKeys[0] = "\"" + Password + "\"";
}
}
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
// wpa
if (Type == WifiCipherType.WIFICIPHER_WPA) {
config.preSharedKey = "\"" + Password + "\"";
config.hiddenSSID = true;
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.OPEN);
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.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
}
return config;
}
// 打开wifi功能
private boolean openWifi() {
boolean bRet = true;
if (!wifiManager.isWifiEnabled()) {
bRet = wifiManager.setWifiEnabled(true);
}
return bRet;
}
class ConnectRunnable implements Runnable {
private String ssid;
private String password;
private WifiCipherType type;
private ProgressDialogUtil progress;
private String ipAddress;
private String gateway;
private String dns;
public ConnectRunnable(String ssid, String password, WifiCipherType type,
String ipAddress, String gateway, String dns,
ProgressDialogUtil progress) {
this.ssid = ssid;
this.password = password;
this.type = type;
this.progress = progress;
this.ipAddress = ipAddress;
this.gateway = gateway;
this.dns = dns;
}
@Override
public void run() {
try {
// 打开wifi
openWifi();
Thread.sleep(200);
// 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
// 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
try {
// 为了避免程序一直while循环,让它睡个100毫秒检测……
Thread.sleep(100);
} catch (InterruptedException ie) {
}
}
WifiConfiguration wifiConfig = createWifiInfo(ssid, password,
type);
//
if (wifiConfig == null) {
return;
}
WifiConfiguration tempConfig = isExsits(ssid);
if (tempConfig != null) {
wifiManager.removeNetwork(tempConfig.networkId);
}
int netID = wifiManager.addNetwork(wifiConfig);
boolean enabled = wifiManager.enableNetwork(netID, true);
boolean connected = wifiManager.reconnect();
LogUtils.printLog("wifi链接--enabled=" + enabled + "---connected=" + connected);
if (enabled && connected){
Num = 0;
Thread.sleep(1000);
IPUtils.getIntance().connetWifi(wifiManager, wifiConfig, ipAddress, gateway, dns, progress);
}else {
if (Num < 3){
Num ++;
connect(ssid, password, type, ipAddress, gateway, dns, progress);
}else {
if (progress != null){
progress.dismiss();
LogUtils.printLog("连接WiFi失败");
}
}
}
} catch (Exception e) {
if (progress != null){
progress.dismiss();
}
LogUtils.printLog("连接WiFi失败---Exception--" + e.getMessage());
e.printStackTrace();
}
}
}
private static boolean isHexWepKey(String wepKey) {
final int len = wepKey.length();
// WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
if (len != 10 && len != 26 && len != 58) {
return false;
}
return isHex(wepKey);
}
private static boolean isHex(String key) {
for (int i = key.length() - 1; i >= 0; i--) {
final char c = key.charAt(i);
if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
&& c <= 'f')) {
return false;
}
}
return true;
}
public void connetWifi(WifiManager mwifiManager, WifiConfiguration mWifiConfiguration, String ipAddress,
String gateway, String dns, ProgressDialogUtil progress){
try {
setStaticIpConfiguration(mwifiManager, mWifiConfiguration,
InetAddress.getByName(ipAddress), 24,//IP 网络前缀长度24
InetAddress.getByName(gateway),//DNS1域名1 gateway
InetAddress.getAllByName(dns), progress);//网关
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public void setStaticIpConfiguration(final WifiManager manager,
WifiConfiguration config, InetAddress ipAddress, int prefixLength,
InetAddress gateway, InetAddress[] dns, ProgressDialogUtil progress)
throws ClassNotFoundException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, NoSuchFieldException, InstantiationException {
// First set up IpAssignment to STATIC.
Object ipAssignment = getEnumValue(
"android.net.IpConfiguration$IpAssignment", "STATIC");
callMethod(config, "setIpAssignment",
new String[] { "android.net.IpConfiguration$IpAssignment" },
new Object[] { ipAssignment });
// Then set properties in StaticIpConfiguration.
Object staticIpConfig = newInstance("android.net.StaticIpConfiguration");
Object linkAddress = newInstance("android.net.LinkAddress",
new Class[] { InetAddress.class, int.class }, new Object[] {
ipAddress, prefixLength });
setField(staticIpConfig, "ipAddress", linkAddress);
setField(staticIpConfig, "gateway", gateway);
ArrayList<Object> aa = (ArrayList<Object>) getField(staticIpConfig,
"dnsServers");
aa.clear();
for (int i = 0; i < dns.length; i++)
aa.add(dns[i]);
callMethod(config, "setStaticIpConfiguration",
new String[] { "android.net.StaticIpConfiguration" },
new Object[] { staticIpConfig });
int updateNetwork = manager.updateNetwork(config);
boolean saveConfiguration = manager.saveConfiguration();
int netId = manager.addNetwork(config);
manager.disableNetwork(netId);
boolean flag = manager.enableNetwork(netId, true);
if (flag){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LogUtils.printLog("连接WiFi成功");
}else {
isConnetWifi = false;
LogUtils.printLog("连接WiFi失败 --IP不可用");
}
}
private static Object newInstance(String className)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, NoSuchMethodException,
IllegalArgumentException, InvocationTargetException {
return newInstance(className, new Class[0], new Object[0]);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static Object newInstance(String className,
Class[] parameterClasses, Object[] parameterValues)
throws NoSuchMethodException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, ClassNotFoundException {
Class clz = Class.forName(className);
Constructor constructor = clz.getConstructor(parameterClasses);
return constructor.newInstance(parameterValues);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object getEnumValue(String enumClassName, String enumValue)
throws ClassNotFoundException {
Class enumClz = (Class) Class.forName(enumClassName);
return Enum.valueOf(enumClz, enumValue);
}
private static void setField(Object object, String fieldName, Object value)
throws IllegalAccessException, IllegalArgumentException,
NoSuchFieldException {
Field field = object.getClass().getDeclaredField(fieldName);
field.set(object, value);
}
private static Object getField(Object object, String fieldName)
throws IllegalAccessException, IllegalArgumentException,
NoSuchFieldException {
Field field = object.getClass().getDeclaredField(fieldName);
Object out = field.get(object);
return out;
}
@SuppressWarnings("rawtypes")
private static void callMethod(Object object, String methodName,
String[] parameterTypes, Object[] parameterValues)
throws ClassNotFoundException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException,
NoSuchMethodException {
Class[] parameterClasses = new Class[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++)
parameterClasses[i] = Class.forName(parameterTypes[i]);
Method method = object.getClass().getDeclaredMethod(methodName,
parameterClasses);
method.invoke(object, parameterValues);
}
public String intToIp(int ipAddress) {
return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
+ (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
}
}