wifiManager.startScan已被弃用
时间: 2024-03-27 18:40:42 浏览: 292
Arduino-WiFiManager.zip
是的,从Android 9(API级别28)开始,`WifiManager.startScan()`已被标记为过时。取而代之的是`WifiManager.startScan()`方法的替代方法`WifiManager.getScanResults()`。
以下是一个更新后的示例代码:
```java
public class WifiScanner extends AppCompatActivity {
private WifiManager wifiManager;
private List<ScanResult> scanResults;
private StringBuilder stringBuilder = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_scanner);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
Button scanButton = findViewById(R.id.scanButton);
scanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scanWifi();
}
});
TextView wifiListTextView = findViewById(R.id.wifiListTextView);
wifiListTextView.setMovementMethod(new ScrollingMovementMethod());
}
private void scanWifi() {
stringBuilder = new StringBuilder();
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
wifiManager.startScan();
Toast.makeText(this, "Scanning WiFi ...", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
scanResults = wifiManager.getScanResults();
for (ScanResult scanResult : scanResults) {
stringBuilder.append("SSID: ")
.append(scanResult.SSID)
.append(" , BSSID: ")
.append(scanResult.BSSID)
.append(" , RSSI: ")
.append(scanResult.level)
.append("\n\n");
}
TextView wifiListTextView = findViewById(R.id.wifiListTextView);
wifiListTextView.setText(stringBuilder.toString());
}
}, 5000); // 5 seconds delay
}
}
```
在此示例中,我们使用了`WifiManager.getScanResults()`方法来获取扫描结果。我们还使用了`Handler`来添加5秒的延迟,以便给WiFi扫描一些时间来完成。一旦扫描完成,我们遍历每个扫描结果,并将它们附加到`StringBuilder`中,最后将其显示在TextView中。
虽然`WifiManager.startScan()`仍然可以在Android 10及更低版本中使用,但我们建议使用`WifiManager.getScanResults()`,以确保代码在未来的Android版本中仍然可以正常工作。
阅读全文