编程实现 Android 手机上 WiFi 操作,编写蓝牙管理与搜索程序,完成蓝牙启动及配对任务
时间: 2023-08-11 21:04:32 浏览: 143
实现Android手机上WiFi操作:
1. 获取WiFi管理器
```
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
```
2. 判断WiFi是否已经打开
```
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
```
3. 扫描WiFi列表
```
wifiManager.startScan();
List<ScanResult> scanResults = wifiManager.getScanResults();
```
4. 连接到指定WiFi网络
```
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + ssid + "\"";
wifiConfig.preSharedKey = "\"" + password + "\"";
wifiManager.addNetwork(wifiConfig);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
```
编写蓝牙管理与搜索程序:
1. 获取蓝牙适配器
```
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
```
2. 判断蓝牙是否已经打开
```
if (!bluetoothAdapter.isEnabled()) {
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BT);
}
```
3. 搜索蓝牙设备
```
bluetoothAdapter.startDiscovery();
```
4. 设置蓝牙可检测性
```
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
```
5. 配对蓝牙设备
```
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
device.createBond();
```
阅读全文