Android 蓝牙通信
时间: 2024-01-19 19:17:45 浏览: 86
Android蓝牙通信可以通过使用Android的蓝牙API来实现。以下是一个简单的示例,演示了如何在Android设备上进行蓝牙通信:
1. 首先,确保在AndroidManifest.xml文件中添加了蓝牙权限:
```xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
```
2. 在你的Activity中,你需要获取BluetoothAdapter实例并启用蓝牙:
```java
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
// 处理不支持蓝牙的情况
} else {
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
```
3. 扫描并获取附近的蓝牙设备:
```java
private final BroadcastReceiver bluetoothReceiver = 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);
// 处理找到的蓝牙设备
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(bluetoothReceiver, filter);
bluetoothAdapter.startDiscovery();
```
4. 连接到选定的蓝牙设备:
```java
BluetoothDevice device = ...; // 通过扫描获得的蓝牙设备
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
```
5. 发送和接收数据:
```java
OutputStream outputStream = socket.getOutputStream();
outputStream.write("Hello, Bluetooth!".getBytes());
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
String receivedData = new String(buffer, 0, bytesRead);
```
请注意,这只是一个简单的示例,实际的蓝牙通信可能涉及更多的步骤和错误处理。你可以根据你的具体需求进行更多的研究和开发。
阅读全文