Home > android, wifi > Scanning the Wi-Fi network

Scanning the Wi-Fi network

Scanning the Wi-Fi network neighbourhood in Android is really easy.

The root class for managing Wi-Fi connectivity is android.net.wifi.WifiManager.
An instance of this class can be obtained from Context like so:

Context context = ...WifiManager wfMgr = (WifiManager) context.
        getSystemService(Context.WIFI_SERVICE);

Scanning is asynchronous. It is initiated by calling WifiManager.startScan(), which returns immediately. Once the scan is complete, Android fires an intent action to notify the application. At this point, scan result can be obtained by calling WifiManager.getScanResults().

Putting it all together might look something like:

public class WifiScanActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ... some code here ...
        mScanReceiver = new ScanResultReceiver();  // register later
    }
    @Override
    protected void onResume(){
        super.onResume();
        registerReceiver(mScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }
    @Override
    protected void onPause(){
        unregisterReceiver(mScanReceiver);
        super.onPause();
    }

    ScanResultReceiver mScanReceiver;
    List mScanResults;

    void onScanListResultsAvailable(Context context)    {
        WifiManager wfMgr = (WifiManager) context.
            getSystemService(Context.WIFI_SERVICE);
        mScanResults = wfMgr.getScanResults();
        // ... scan results are available at this point
    }

    // A helper class to receive end of scan notification
    class ScanResultReceiver extends BroadcastReceiver    {
        @Override
        public void onReceive(Context context, Intent intent) {
            // call the enclosing activity class
            onScanListResultsAvailable(context);
        }
    }
}

Note that the broadcast receiver is only active when the activity is active. This is facilitated by registering it in the activity’s onResume() and unregistering in onSuspend(). Note that onResume() is called even when the activity is initially activated. Very covenient!

Advertisements
Categories: android, wifi
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s