猛禽洛的程式筆記庫

[Android] 掃描周圍的WiFi訊號

1.新增權限(如果Android版本6.0以上必須實作動態取得權限)

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

 

2.主程式部分

private WiFiManager mWiFiManager;
private List<ScanResult> results;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  ...
  ...
  wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
  if(!wifiManager.isWifiEnabled()){
    //WiFi未開啟的話,打開它
    wifiManager.setWifiEnabled(true);
  }
  //開始進行掃描
  scanWifi();
  
}

private void scanWifi(){
  registerReceiver(new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      wifiScanReceive();
    }
  }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
  wifiManager.startScan();
}

private void wifiScanReceive(){
  // the result.size() is 0 after update to Android v6.0, same code working in older devices.
  results =  wifiManager.getScanResults();

  int size = results.size();
  Toast.makeText(this,"scan result :" + size,Toast.LENGTH_SHORT).show();

  for(int i = 0 ; i <size  ; i++ ){
    //手機目前周圍的Wi-Fi環境
    String SSID  = results.get(i).SSID ;
    int LEVEL = results.get(i).level;
    String item = String.format("%s-%d",SSID,LEVEL);
    Log.d("wifi",item);
  }
}

-END-

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *