android Rwifi扫描Demo
时间: 2023-07-22 17:44:24 浏览: 99
Android WIFI扫描Demo.rar
5星 · 资源好评率100%
以下是一个简单的Android WiFi扫描的Demo:
首先,在你的AndroidManifest.xml文件中添加以下权限:
```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_COARSE_LOCATION"/>
```
然后,创建一个名为WifiScanner的Activity,并在其布局文件中添加一个Button和一个TextView:
WifiScanner.java:
```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);
}
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
Toast.makeText(this, "Scanning WiFi ...", Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
scanResults = wifiManager.getScanResults();
unregisterReceiver(this);
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());
}
};
}
```
activity_wifi_scanner.xml:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/scanButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Scan WiFi"/>
<TextView
android:id="@+id/wifiListTextView"
android:layout_below="@id/scanButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:textColor="#000000"
android:textSize="18sp"
android:scrollbars="vertical"/>
</RelativeLayout>
```
这个Demo中,我们使用了WifiManager来扫描WiFi网络。当用户点击“Scan WiFi”按钮时,我们将启动一个广播接收器来接收扫描结果。接收到结果后,我们将遍历所有的扫描结果,并将它们显示在TextView中。
请注意,WiFi扫描可能需要一些时间,具体取决于您的设备和周围的网络环境。因此,您应该在用户点击按钮后显示一个Toast消息,以提示他们正在进行WiFi扫描。
阅读全文