We are trying to switch ON wifi hotspot programatically but sometimes it goes in an infinite loop and does not switch ON but mostly it works. This is the line where it hangs "while (!(Boolean) isWifiApEnabledMethod.invoke(wifiManager)) { Thread.sleep(500); };" Entire code is placed below. This is only a problem with Android 5.0/5.1 devices. Any inputs will be appreciated.
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);
}
We explored further and we get better behavior when we use this method
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; } }
Thanks