我们正在尝试以编程方式打开 wifi 热点,但有时它会进入无限循环并且不会打开,但大多数情况下它可以工作。这是它挂起的行“while (!(Boolean) isWifiApEnabledMethod.invoke(wifiManager)) { Thread.sleep(500); };” 整个代码放在下面。这只是 Android 5.0/5.1 设备的问题。任何输入将不胜感激。
WifiManager wifiManager = (WifiManager)getActivity().getApplicationContext().getSystemService (Context.WIFI_SERVICE);
//If Wifi is ON then switch it OFF
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
WifiConfiguration netConfig = new WifiConfiguration();
Random random = new Random();
int iRandomKey = random.nextInt(65536);
netConfig.SSID = "TestHotspot";
netConfig.status = WifiConfiguration.Status.ENABLED;
netConfig.priority = 40;
//hiding SSID,
netConfig.hiddenSSID = true;
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
netConfig.preSharedKey = "testpassword";
final String RingOfFire_Ssid = netConfig.SSID;
final String RingOfFire_password = netConfig.preSharedKey;
try {
Method setWifiApMethod = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
boolean apstatus = (Boolean) setWifiApMethod.invoke(wifiManager, netConfig, true);
Log.d("ConnectWIFI:", "apstatus" + ":" + apstatus);
Method isWifiApEnabledMethod = wifiManager.getClass().getMethod("isWifiApEnabled");
while (!(Boolean) isWifiApEnabledMethod.invoke(wifiManager)) {
Thread.sleep(500);
};
Method getWifiApConfigurationMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
netConfig = (WifiConfiguration) getWifiApConfigurationMethod.invoke(wifiManager);
Log.d("ConnectWIFI:", netConfig.SSID + ":" + netConfig.preSharedKey + ":" + "Hotspot");
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
}
我们进一步探索,当我们使用这种方法时,我们得到了更好的行为
Class<?> cls=WifiManager.class;
for (Method method:cls.getDeclaredMethods()){
String methodName=method.getName();
if (methodName.equals("getWifiApState")){ getWifiApState=method; }
else if (methodName.equals("isWifiApEnabled")){ isWifiApEnabled=method; }
else if (methodName.equals("setWifiApEnabled")){ setWifiApEnabled=method; }
else if (methodName.equals("getWifiApConfiguration")) { getWifiApConfiguration=method; } }
谢谢