android 蓝牙发送数据
时间: 2023-09-02 12:08:37 浏览: 100
在 Android 中通过蓝牙发送数据需要涉及到以下几个步骤:
1. 检查蓝牙是否可用,如果不可用则请求开启蓝牙权限。
2. 扫描附近的蓝牙设备,找到目标设备。
3. 连接目标设备。
4. 发送数据。
下面给出一个简单的例子:
```java
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice targetDevice;
private BluetoothSocket bluetoothSocket;
// 初始化蓝牙
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
return;
}
if (!bluetoothAdapter.isEnabled()) {
// 请求开启蓝牙权限
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
return;
}
// 扫描附近的蓝牙设备
bluetoothAdapter.startDiscovery();
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName().equals("target_device_name")) {
targetDevice = device;
bluetoothAdapter.cancelDiscovery();
}
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
// 连接目标设备
bluetoothSocket = targetDevice.createRfcommSocketToServiceRecord(MY_UUID);
bluetoothSocket.connect();
// 发送数据
OutputStream outputStream = bluetoothSocket.getOutputStream();
outputStream.write("Hello, world!".getBytes());
outputStream.flush();
```
注意,这只是一个简单的例子,实际使用中还需要考虑一些异常情况,例如连接失败、发送失败等。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)