android蓝牙通信
时间: 2023-07-29 18:08:04 浏览: 51
Android蓝牙通信可以通过BluetoothAdapter和BluetoothSocket类来实现。以下是一个简单的示例代码,可以通过蓝牙连接到另一个设备并发送数据:
首先,你需要获取设备的蓝牙适配器:
```
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
```
接下来,你需要启用蓝牙:
```
if (!bluetoothAdapter.isEnabled()) {
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH);
}
```
然后,你需要搜索并连接到其他设备:
```
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
BluetoothDevice device = null;
for (BluetoothDevice pairedDevice : pairedDevices) {
if (pairedDevice.getName().equals("DeviceName")) {
device = pairedDevice;
break;
}
}
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
bluetoothAdapter.cancelDiscovery();
socket.connect();
```
最后,你可以通过输入输出流来发送和接收数据:
```
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
outputStream.write("Hello, world".getBytes());
byte[] buffer = new byte[1024];
int bytes;
while ((bytes = inputStream.read(buffer)) > 0) {
String message = new String(buffer, 0, bytes);
Log.d(TAG, "Received message: " + message);
}
```
当你完成通信后,记得关闭输入输出流和套接字:
```
inputStream.close();
outputStream.close();
socket.close();
```
需要注意的是,蓝牙通信可能会遇到各种问题,例如连接失败或数据传输中断。因此,你需要适当地处理这些异常情况。