Android 经典蓝牙简单集成

1,028 阅读1分钟

蓝牙设备配对

1、设置蓝牙权限

permission.bluetooth
permission.bluetooth_admin
permission.coarse.location

2、检查设备是否支持蓝牙设备

BluetoothAdapter.getDefaultAdapter() == null//该设备不支持蓝牙

3、检查设备是否开启蓝牙

boolean enabled =BluetoothAdapter.getDefaultAdapter().isEnalbed();

//蓝牙未开启,开启蓝牙

if(!enabled) {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, REQUST_BLUETOOTH_OPEN);
}

4、查找设备

查找设备之前 可以检查已经配对设备

Set<BluetoothDevice> devices =  Bluetooth.getDefaultAdapter().getBondedDevices();

查找设备

BluetoothAadpter.getDefaultAdapter().startDiscovery();

该查找设备为异步操作,立即返回boolean通知是否开启查找设备成功。 查找结果注册广播获取(BluetoothDevice,BluetoothClass)

BroadcastReceiver br = new BroadcastReceiver {
    public void onReceive (Context context, Intent intent) {
        switch (action) {
            case BluetoothDevice.ACTION_FOUND://发现设备
                break;
            case BluetoothDevice.ACTION_ACL_CONNECTED://连接成功
                break;
            case BluetoothDevice.ACTION_ACL_DISCONNECTED://断开连接
                break;
            case BluetoothDevice.ACTION_PAIRING_REQUEST://正在配对
                break;
        }
    }
}

5、配对设备

配对设备,作为服务端进行配对(此处仅考虑客户端情况)

作为客户端进行配对

利用拿到到扫描到的BluetoothDevice 以及UUID获取该设备的BluetoothSocket 伪代码:

BluetoothDevice device = new BluetoothDevice();//实际该设备由扫描获取。
BluetoothSocket socket = device.createRfcommSocketToServceRecord(DEVICE_UUID);
socket.connet();//阻塞方法,异步调用

6、设备会话

设备配对后,进行通信会话,利用socket 中的读写流进行会话 socket.getInputStream();//读取(接受设备数据)异步进行 socket.getOutputStream();//发送(发送设备命令),可异步。