In previous post, I have shown how we can start the scanning of wifi and receive the results using BroadcastReceiver. The problem with this approach is it consumes battery each time scanning is started. To avoid this there is another way: Listen to scan results initiated by other applications or by OS.
You need to add following in manifest.
Code for WifiScanCompleteReceiver.java is as follows:
You need to add following in manifest.
<receiver android:name="com.example.receivers.WifiScanCompleteReceiver" > <intent-filter> <action android:name="android.net.wifi.SCAN_RESULTS" /> </intent-filter> </receiver>
Code for WifiScanCompleteReceiver.java is as follows:
package com.example.receivers; //imports public class WifiScanCompleteReceiver extends BroadcastReceiver { public WifiScanCompleteReceiver() {} @ Override public void onReceive(Context context, Intent intent) { Log.d(HelperUtils.getInstance().getApplicationName(), "Wifi scan result received."); Vector < String > WifiNames = new Vector < String > (); WifiManager manager = (WifiManager) Main.getInstance().getContext().getSystemService(Context.WIFI_SERVICE); List < ScanResult > scanResults = manager.getScanResults(); if (scanResults != null) { for (int i = scanResults.size() - 1; i >= 0; i--) { ScanResult result = scanResults.get(i); //Use result.SSID, result.level or result as it suits to your requirements } } } }This receiver will be called even if the application is killed.
No comments:
Post a Comment