public void connectWifiAP(BA ba, String ssid, int security, String password, int timeout) {
if (debug)
BA.Log("SDK: " + Build.VERSION.SDK_INT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
tmr = new Timer();
tmr.schedule(new TimeoutTask(ba), timeout);
connectWifiAP2(ba, ssid, "", security, password);
} else {
connectWifiAPQ(ba, ssid, security, password, timeout);
}
}
static private void connectToWifi(BA ba, WifiManager wm, int NetId, String ssid) {
try {
connectionSuccess = false;
if (debug)
BA.Log("[MLwifi] Connecting to " + ssid);
if (receiverRegistered) {
unregisterReceiver(broadcastReceiver);
}
if (broadcastReceiver == null) {
final IntentFilter intentFilter = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION);
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
if (debug)
BA.Log("BroadcastReceiver Intent Action: " + intent.getAction());
}
// Post connection
@SuppressLint("MissingPermission") NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null) {
if (debug)
BA.Log(networkInfo.toString());
if (networkInfo.isConnected()) { //&& networkInfo.getExtraInfo().equals(ssid)) {
WifiManager wifiManager = (WifiManager) BA.applicationContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
// BA.Log(info.getSSID() + " : " + ssid);
if (info.getSSID().equals(ssid)) {
if (ba.subExists("wifi_connectionresult") && networkInfo.getState() == NetworkInfo.State.CONNECTED && !connectionSuccess) {
connectionSuccess = true;
if (debug)
BA.Log("[MLwifi] Connected to " + info.getSSID());
tmr.cancel();
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new Runnable() {
public void run() {
ba.raiseEvent(this, "wifi_connectionresult", true);
}
}, 1, TimeUnit.SECONDS);
}
// } else {
// if (ba.subExists("wifi_connectionresult")) {
// ba.raiseEvent(this, "wifi_connectionresult", false);
// }
}
} else if (!networkInfo.isAvailable() && networkInfo.getExtraInfo().equals(ssid)) {
tmr.cancel();
if (debug)
BA.Log("[MLwifi] " + ssid + " not available");
if (ba.subExists("wifi_connectionresult")) {
ba.raiseEvent(this, "wifi_connectionresult", false);
}
}
}
}
};
BA.applicationContext.registerReceiver(broadcastReceiver, intentFilter);
receiverRegistered = true;
}
wm.enableNetwork(NetId, true);
} catch (Exception e) {
BA.LogError(e.getLocalizedMessage());
}
}
static class TimeoutTask extends TimerTask {
BA _ba;
public TimeoutTask(BA ba) {
_ba = ba;
}
public void run() {
tmr.cancel(); //Terminate the timer thread
if (_ba.subExists("wifi_connectionresult")) {
_ba.raiseEvent(this, "wifi_connectionresult", false);
}
if (receiverRegistered) {
unregisterReceiver(broadcastReceiver);
}
}
}