蓝牙串口

114 阅读1分钟

读取蓝牙串口数据

需要在AndroidManifest.xml,赋予相关权限

<!-- 必要权限 -->
android.permission.BLUETOOTH  
<!-- 非必要权限 -->
android.permission.BLUETOOTH_CONNECT
android.permission.BLUETOOTH_ADMIN
private BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
private BluetoothSocket bluetoothSocket;
private SerialSocket serialSocket;

1、判断系统蓝牙是否处于开启状态

// 需要加入 android.permission.BLUETOOTH_CONNECT
if (!defaultAdapter.isEnabled()) {
    //make sure the device's bluetooth is enabled
    Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
}

2、连接蓝牙串口并获取串口数据

// 获取蓝牙设备
bluetoothDevice = defaultAdapter.getRemoteDevice(mac);
// 获取蓝牙socket接口
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(SERIAL_UUID);
// 连接蓝牙socket
bluetoothSocket.connect();
// 读取从socket获取的数据
byte[] buffer = new byte[1024];
int len;
//读数据
// noinspection InfiniteLoopStatement
while (true) {
    len = bluetoothSocket.getInputStream().read(buffer);
    byte[] data = Arrays.copyOf(buffer, len);
    String datas = new String(data, StandardCharsets.UTF_8);
    Log.d(TAG, "bluetoothMine: first string: " + datas);
}