Android 10 wifi列表获取

  • Post author:
  • Post category:其他


1、打开WiFi,并打开定位服务(在设置内找到定位服务-访问我的位置信息-开启)

2、在 onCreate 里面动态申请权限

String[] PERMS_INITIAL={Manifest.permission.ACCESS_FINE_LOCATION};
requestPermissions(PERMS_INITIAL,127);

3、在 onCreate 里面注册广播

IntentFilter filter =new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(mReceiver, filter);

4、定义 mReceiver

private BroadcastReceiver mReceiver =new BroadcastReceiver() {
@Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            List results =wifiManager.getScanResults();
            if (results !=null) {
                Log.d(TAG,"results size: " + results.size());
            }
        }
    }
};

5、在layout里面定义一个Button,点击后开始扫描

WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
boolean scanResult = wifiManager.startScan(); //最好检查下返回值,因为这个方法可能会调用失败
Log.d(TAG,"scanResult: " + scanResult);

6、在 AndroidManifest.xml 里面声明权限

<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_FINE_LOCATION"/>


错误用法:

boolean scanResult = wifiManager.startScan();
List list =wifiManager.getScanResults();


调用 startScan 之后立马调用 getScanResults,这个时候拿到的WiFi列表是上一次的扫描结果,不是最新的,一定要在广播接收器里面获取扫描结果

注意:手机设备中的定位服务要打开,否则获取不到wifi列表