Questions:
In the previous article, there was another problem: Wifimanager's Startscan () method is returned immediately, which means that the method calls a thread that scans the WiFi signal, so when does this scan end? When do we call Wifimanager's Getscanresults () to get the scan results?
Answer:
When the Wifimanager Startscan () method is called, the system emits a wifimanager.scan_results_available_action broadcast after the scan is finished. So we just have to set a broadcastrecever to accept the broadcast on the line. My mobile phone test, almost scan to spend about 1s.
1. Define a broadcastrecever to process the scan results, and when the scan is finished, the OnReceive () method is called.
Note: wifimanager.scan_results_available_action This listener, if there is wifi available, and there is no WiFi, will automatically trigger the OnReceive () method, once the connection is successful is not executed.
1 //result processing class after WiFi scan is finished2 Private Final classWifireceiverextendsbroadcastreceiver{3 //This method is triggered when the scan is finished4 Public voidOnReceive (Context context, Intent Intent) {5List<scanresult> scanlist =wm.getscanresults ();6 for(Scanresult scanresult:scanlist) {7 //actions on the scan results8 9 }Ten } One}
2, registration services, cancellation services. It is recommended that the services be registered and unregistered in Onresume () and OnPause () respectively.
1 Public voidOnresume () {2 Super. Onresume ();3Registerreceiver (Wifireceiver,NewIntentfilter (wifimanager.scan_results_available_action));//Registration Services4 }5 protected voidOnPause () {6 Super. OnPause ();7Unregisterreceiver (Wifireceiver);//Cancel Registration8}