Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To check whether the wifi scan is complete

I'm writing a code for getting the information of all the access points in the range continuously.

Here is my code:

       myRunnable = new Runnable() {
       @Override public void run() {
       while(){
       wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
       wifi.startScan(); 
       List<ScanResult>results= wifi.getScanResults();
        try{
          //data Logging
            }  
           } 
         } 
        };

      myThread = new Thread(myRunnable);
      myThread.start();

As the scanning and logging of data continuous repeatedly, i want to check whether the scan is complete before logging data. Is there any flag or function which checks for wifi.startScan() is complete or not , before logging the data. Could you please help me out with a code.

like image 999
user2334777 Avatar asked Mar 23 '23 04:03

user2334777


2 Answers

i want to check whether the scan is complete before logging data. Is there any flag or function which checks for wifi.startScan() is complete or not , before logging the data. Could you please help me out with a code.

Yes, there is mechanizm designated for this purpose. To reach your goal you need to implement BroadcastReceiver that will listen for WiFi scans.

All what you need is to create BroadcastReceiver with appropriate IntentFilter. So you need this action for filter:

WifiManager.SCAN_RESULTS_AVAILABLE_ACTION

This action means that an access point scan has completed, and results are available. And then just create BroadcastReceiver (statically or dynamically, it's doesn't matter).

If you don't know how to start, look at this tutorial:

  • Android BroadcastReceiver Tutorial
like image 153
Simon Dorociak Avatar answered Apr 10 '23 07:04

Simon Dorociak


To build up on the answers above, I just wanted to add the related code to give an example.

1. Registering for the event

// don't forget to set permission to manifest
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
context.registerReceiver(this,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
//check if WIFI is enabled and whether scanning launched
if(!wifiManager.isWifiEnabled() || !wifiManager.startScan())
{
  throw new Exception("WIFI is not enabled");
}

2. Receiving the result

To receive, the object registered (in this case this) needs to extend BroadcastReceiver and implement the following method:

public void onReceive(Context context, Intent intent) {
        List<ScanResult> result = wifiManager.getScanResults();
 } 
like image 34
Sebastian Hojas Avatar answered Apr 10 '23 07:04

Sebastian Hojas