android studio蓝牙通讯代码
时间: 2023-12-21 18:03:18 浏览: 98
以下是一个基于Android Studio的蓝牙通讯代码示例:
```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);
}
}
// 搜索蓝牙设备
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC地址
}
}
// 监听蓝牙连接
private final BroadcastReceiver receiver = 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);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC地址
}
}
};
// 连接蓝牙设备
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
// 通过蓝牙发送消息
OutputStream outputStream = socket.getOutputStream();
outputStream.write(message.getBytes());
// 通过蓝牙接收消息
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
String incomingMessage = new String(buffer,0, bytes);
} catch (IOException e) {
break;
}
}
```
阅读全文