I have also got the same problem. I solved it by the help of broadcast receiver and build my own logic around it.
Broadcast Receiver class, make sure for provided permissions ACCESS_WIFI_STATE and CHANGE_WIFI_STATE in manifest.
public class WifiChecker extends BroadcastReceiver {
private OnWifiResultArrived onWifiResultArrived = null;
private static boolean CAN_CALL_AGAIN = true;
private WifiManager wifiManager;
/**
* @param context context of activity.
* Remember to provide permission
* <p>
* {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />},
* {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />}</p>
*/
@SuppressLint("MissingPermission")
public WifiChecker(Context context) {
CAN_CALL_AGAIN = true;
wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
context.registerReceiver(this, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
rerunAgain();
}
private void rerunAgain() {
new Handler().postDelayed(new Runnable() {
@SuppressLint("MissingPermission")
@Override
public void run() {
if (CAN_CALL_AGAIN)
wifiManager.startScan();
rerunAgain(); //rerun the broadcast again
}
}, 1000);
}
public void addListerForWifiCallback(OnWifiResultArrived onWifiResultArrived) {
this.onWifiResultArrived = onWifiResultArrived;
}
@SuppressLint("MissingPermission")
@Override
public void onReceive(Context context, Intent intent) {
updateUi(wifiManager.getScanResults());
}
private void updateUi(final List<ScanResult> scanResults) {
try {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
if (onWifiResultArrived != null)
onWifiResultArrived.isInWifiRange(scanResults);
} catch (Exception e) {
e.printStackTrace();
}
}
}, 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
public void unregisterListner(Context context) {
this.onWifiResultArrived = null;
CAN_CALL_AGAIN = false;
}
public interface OnWifiResultArrived {
void isInWifiRange(List<ScanResult> scanResults);
}
}
User of Broadcast class
Either implement the broadcast receiver class interface i.e.,OnWifiResultArrived
WifiChecker checker = new WifiChecker(this);
checker.addListerForWifiCallback(this);
@Override
public void isInWifiRange(List<ScanResult> scanResults){
//get your BSSID here
scanResults.get(position).BSSID;
//write your logic for checking weather it is connected or not
}
or
WifiChecker checker = new WifiChecker(this);
checker.addListerForWifiCallback(@Override
public void isInWifiRange(List<ScanResult> scanResults){
//get your BSSID here
scanResults.get(position).BSSID;
//write your logic for checking weather it is connected or not
});