Reputation: 102
I have this inside a Timer:
if (wManager.startScan()) {
try {
//Following method is one I call to process the results
acquireCurrentZoneFromServer.run(client, wManager.getScanResults());
} catch (Exception e) {
e.printStackTrace();
}
}
This works fine. However, when I set the Timer to run in small intervals, such as 1 second, the results I get are repeated in groups of 2. Any workaround on this?
Upvotes: 0
Views: 1043
Reputation: 3922
I think, your solution is wrong. You don't need to check for the scan results every 1 second or any other interval. You should create BroadcastReceiver. BroadcastReceiver will notify your app when it gets the scan results. Method named startScan()
does not guarantee the time of delivery of the results. When you try to read scan results every 1 second, it's not deterministic. You may receive something, but you also may not. Nevertheless, the timer is going, what reduces performance and drains the battery, so this solution is not so efficient.
Here's exemplary code snippet presenting the idea:
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.startScan(); // without starting scan, we may never receive any scan results
final IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.RSSI_CHANGED_ACTION); // you can keep this filter if you want to get fresh results when singnal stregth of the APs was changed
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
wifiManager.startScan();
final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
wifiManager.startScan(); // start scan again to get fresh results ASAP
wifiManager.getScanResults();
}
};
context.registerReceiver(receiver, filter);
// don't forget to unregister receiver when appropriate
// context.unregisterReceiver(receiver);
You can adjust this snippet to your needs.
If you want to, you can also use my library called ReactiveWiFi available at https://github.com/pwittchen/ReactiveWiFi. It allows you to monitor change of the WiFi access points with RxJava Observables as follows:
new ReactiveWifi().observeWifiAccessPoints(context)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<ScanResult>>() {
@Override public void call(List<ScanResult> scanResults) {
// do something with scanResults
}
});
This solution also uses BroadcastReceiver under the hood similar to the first code snippet, but it's wrapped with observable, so usage is simpler.
Upvotes: 3