扫描接入点

此示例扫描可用的接入点和 ad hoc 网络。btnScan 激活 WifiManager.startScan() 方法启动的扫描。扫描后,WifiManager 调用 SCAN_RESULTS_AVAILABLE_ACTION intent,WifiScanReceiver 类处理扫描结果。结果显示在 TextView 中。

public class MainActivity extends AppCompatActivity {

    private final static String TAG = "MainActivity";

    TextView txtWifiInfo;
    WifiManager wifi;
    WifiScanReceiver wifiReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
        wifiReceiver = new WifiScanReceiver();

        txtWifiInfo = (TextView)findViewById(R.id.txtWifiInfo);
        Button btnScan = (Button)findViewById(R.id.btnScan);
        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "Start scan...");
                wifi.startScan();
            }
        });
    }

    protected void onPause() {
        unregisterReceiver(wifiReceiver);
        super.onPause();
    }

    protected void onResume() {
        registerReceiver(
            wifiReceiver, 
            new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
        );
        super.onResume();
    }

    private class WifiScanReceiver extends BroadcastReceiver {
        public void onReceive(Context c, Intent intent) {
            List<ScanResult> wifiScanList = wifi.getScanResults();
            txtWifiInfo.setText("");
            for(int i = 0; i < wifiScanList.size(); i++){
                String info = ((wifiScanList.get(i)).toString());
                txtWifiInfo.append(info+"\n\n");
            }
        }
    }
}

权限

需要在 AndroidManifest.xml 中定义以下权限 :

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

android.permission.ACCESS_WIFI_STATE 是调用 WifiManager.getScanResults() 所必需的。如果没有 android.permission.CHANGE_WIFI_STATE,你就无法使用 WifiManager.startScan() 进行扫描。

在为 api level 23 或更高版本(Android 6.0 及更高版本)编译项目时,必须插入 android.permission.ACCESS_FINE_LOCATIONandroid.permission.ACCESS_COARSE_LOCATION。此外,需要请求权限,例如在主要活动的 onCreate 方法中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    String[] PERMS_INITIAL={
            Manifest.permission.ACCESS_FINE_LOCATION,
    };
    ActivityCompat.requestPermissions(this, PERMS_INITIAL, 127);
}