Android gets connectable wifi and wifi signal strength

1. You need to add permissions in AndroidManifest.xml

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

Depending on the android system, you also need to add and apply for location permissions

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

Otherwise, wifiManager.getScanResults() cannot get any data;

2. Please set the android settings to enable WLAN

private void startScanWifi() {

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    wifiManager.startScan();

    List<ScanResult> resultList = wifiManager.getScanResults();

    ScanResult scanResult;
    String SSID;
    int rssi;
    int level;
    if (resultList != null && resultList.size() > 0) {
        for (int i = 0; i < resultList.size(); i++) {

            scanResult = resultList.get(i);
            //name
            SSID = scanResult.SSID;
            //Signal strength, the obtained value is an interval value from 0 to -100, which is an int type data
            rssi = scanResult.level;
            //Signal strength level, according to the strength value, divided into 6 levels, 5 is the largest, indicating the highest strength
            level = WifiManager.calculateSignalLevel(rssi, 6);
         
        }
    }

}

resultList is the result of the wifi list that can be connected

3. Obtain the connected wifi

private WifiResultInfo getConnectedWifi() {
    
    WifiResultInfo wifiResultInfo = null;

    WifiInfo wifiInfo = wifiManager.getConnectionInfo();

    if (wifiInfo != null) {
        String ssid = wifiInfo.getSSID();
        int rssi = wifiInfo.getRssi();

        if(ssid.startsWith("\"") && ssid.endsWith("\""))
        {
            ssid = ssid.substring(1, ssid.length() - 1);
        }
   
    }
    return wifiResultInfo;
}

おすすめ

転載: blog.csdn.net/chongchi_wxcc/article/details/126941037