掃描接入點

此示例掃描可用的接入點和 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);
}