主要流程:
通过广播中获取信息
初始化、发起扫描:
mainWifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
在广播中接收信息:
@SuppressWarnings("all")
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
for (int i = 0; i < wifiList.size(); i++) {
sb.append(new Integer(i + 1).toString() + ".");
ScanResult scanResult = wifiList.get(i);
sb.append("" + scanResult.SSID);
sb.append("\n\n");
}
Log.d("xiaocai", "onReceive sb:" + sb.toString());
mainText.setText(sb);
}
}
注销广播:
protected void onPause() {
super.onPause();
unregisterReceiver(receiverWifi);
}
protected void onResume() {
super.onResume();
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
需要的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
log 显示:
onReceive sb:1.my3579
2.PandoraBox-5G-3D73AE
...
15.my3579
16.
17.ChinaNet-nKSm
18.FKET
19.boardroom
备注: 有些wifi是没有名称的(名称为空)