android蓝牙BLE开发

BLE简介

ble是指低功耗蓝牙,谷歌在Android4.3版本的时候加入了低功耗蓝牙的api,随着蓝牙的发展,低功耗成为了主要的方向。低功耗蓝牙的出现让市面上的电子产品越来越人性化,出现了智能手环,也使得我们的生活越来越离不开低功耗蓝牙,废话不多说,直接看BLE的开发步骤吧

1.需要的权限

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Android6.0以上还需要位置权限,一下权限只需要一个即可,一般来说这个权限在6.0以上需要动态注册,但是部分并不能通过动态注册获取该权限,所以这需要开发者自己去适配机型了

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

2.获取蓝牙适配器对象

在Android 4.2以前只能通过BluetoothAdapter静态方法getDefaultAdapter()方法来获取到蓝牙适配器对象,但是4.3以后也可以使用getSystemService(Context.BLUETOOTH_SERVICE)获取到BluetoothManager对象,然后再通过BluetoothManager对象的getAdapter()方法获取到适配器对象

mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null)//如果为空,你的手机可能不支持蓝牙
    return;
mBluetoothAdapter = mBluetoothManager.getAdapter();

3.扫描设备

获取到蓝牙适配器对象之后就可以通过bluetoothAdapter.startScan(UUID[] serviceUuids, BluetoothAdapter.LeScanCallback)方法来就行扫描了,其中可以通过设置第一个参数来过虑掉一些不需要的设备,第二个参数则是扫描的设备的回调接口,扫描到设备的地方尽量少做操作,避免遇到不必要的麻烦,如果有特别多的计算量,建议开启一个子线程

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        mBluetoothAdapter.stopLeScan(scanCallback);//扫描10s后停止扫描,不然会一直进行扫描,非常消耗内存
    }
}, 5000);
mBluetoothAdapter.startLeScan(scanCallback);

4.连接设备

在通过步骤3扫描到设备时,我们就可以获取到BluetoothDevice对象了,当然如果你有目标设备地址的话也可以通过BluetoothAdapter的getRemoteDevice()方法来获取到BluetoothDevice对象。拿到了BluetoothDevice对象后掉用BluetoothDevice对象的connectGatt(Context, boolean,BluetoothGattCallback)方法即可进行连接了(建议在主线程进行连接,不然可能会遇到意想不到的麻烦,特别是Android这样开源的系统,总有那么一两款手机让你欲哭无泪),连接或断开时会通过BluetoothGattCallback 接口的onConnectionStateChange(BluetoothGattt, int, int)方法回调连接或断开连接的信息。断开连接通过调用disconne()方法,当然两个蓝牙离开一定的距离也会自动断开。断开之后必须调用close()关闭BluetoothGatt对象,不然可能会受到蓝牙连接个数的限制。

5.数据交互

Ble两蓝牙间的数据通讯基本上也都靠BluetoothGatt对象了,而在数据交互时BluetoothGattCharacteristic和BluetoothGattDescriptor是重要的属性,而BluetoothGattDesctiptor是BluetoothGattCharacteristic对象的重要属性,只要获得BluetoothGattCharacteristic对象可以获得BluetoothGattDesctiptor对象了,而BluetoothGattCharacteristic又是BluetoothGattService的属性,所以在数据交互前我们必须通过BluetoothGatt.discoverServices()发现服务,然后拿到以上对象才能进行数据交互。在数据交互过程中一般完成一个交互动作都会有一个通知回调,设置通知回调通过BluetoothGatt.setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable),但是chanrateristic需要设置一个Descriptor属性值BluetoothGattDesctiptor.ENABLE_NOTIFICATION_VALUE,不然写入数据是没有反应的。在连接多个蓝牙时,在对蓝牙操作的过程中最好将操作统一添加到一个队列中,完成一个操作再执行下一个操作,不然部分操作可能会被阻塞,其中包括对多个蓝牙的连接,最好连接上一个再去连接下一个。

需要注意的是在发送数据的时候,只能一次发送20byte的报文,如果大于这个数,则需要分包发送

猜你喜欢

转载自blog.csdn.net/weixin_38358978/article/details/82156046