Android 低功耗蓝牙简单集成记录

333 阅读1分钟

蓝牙低功耗开发

1、低功耗蓝牙权限

permission.BLUETOOTH
permission.BLUETOOTH_ADMIN
//api >= 23
permission.ACCESS_FIND_LOCATION
permission.ACCESS_COARSE_LOCATION

2、确认设备是否支持低功耗蓝牙

1、应用仅运行在支持低功耗蓝牙设备,清单配置

<use-feature android:name="android.hardware.bluetooth_le" android:required="true" />

2、android:required="false" ,情况下应用内部判断是否支持低功耗蓝牙

if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
    //不支持低功耗蓝牙,关闭所有低功耗蓝牙功能
}

3、确认设备是否开启低功耗蓝牙

1、获取蓝牙适配器

//api >= 18
BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE)
BluetoothAdapter bluetoothAdapter = bluetoothManager.getBluetoothAdapter();

2、判断蓝牙是否开启

if(!bluetoothAdapter.isEnabled()){
    startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0x001);
}

4、扫描低功耗蓝牙设备,获取设备列表

获取低功耗蓝牙设备startLeScan(),接受一个LeScanCallback 扫描结果回调参数 注意:找到设备立即停止扫描,扫描超时立即停止扫描。

bluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback () {
    public void onLeScan(BluetoothDevice deivce, int rssi, byte[] sacnRecord) {
        //扫描结果
    }
})

5、连接指定低功耗蓝牙设备

连接一个低功耗蓝牙设备一般分为一下步骤 1、连接GATT

gattCallback = new BluetoothGattCallback() {
    //gatt 连接状态改变
    public void onConnectionStateChanged(BluetoothGatt gatt, int state, int newState) {
        //newState: 当前连接Gatt状态
        //newState == connected,获取gatt实例,发现Gatt 中的 Service
        gatt.discoverServices();
    }
    //service 被发现
    public void onServiceDiscovered (BluetoothGatt gatt, int state) {
        //state == Gatt_Connected
    }
    //Characteristics 特性被加载
    public void onCharacteristicRead(BluetoothGatt gatt, Characteristics characteristics, int state) {
        //state == Gatt_success
    }
}
device.connectGATT(context, autoConnect, gattCallback);

2、发现GATT 中的Service

gatt.discoverServices();

3、获取Service中的Characteristics

services = mBluetoothLeService.getSupportedGattServices();//获取gatt支持的所有service也可以利用股uid获取指定service
services.getCharacteristics();

//获取指定service所有Charactistics,也可根据uuid获取指定Characteristics.

6、与已连接低功耗蓝牙设备进行数据通信

利用该Characteristics 设置gatt的Characteristics 的通知监听 触发onCharacteristics 进行数据通信

7、低功耗蓝牙设备状态通知

略。