安卓BLE蓝牙开发详解

前言

BLE蓝牙的兴起主要因为近年来可穿戴设备的流行。由于传统蓝牙功耗高不能满足可穿戴设备对于续航的要求。所以大部分可穿戴设备采用蓝牙4.0,即BLE蓝牙技术。BLE(Bluetooth Low Energy)低功耗蓝牙,主要特点是快速搜索,快速连接,超低功耗保持连接和数据传输。
缺点:BLE蓝牙数据传输速率低,特别是在安卓开发过程,BLE蓝牙一包数据最多为20字节,因此安卓系统下最好不要使用BLE蓝牙传输大量数据。

蓝牙开发的主要流程

(一)申请权限

安卓手机涉及蓝牙权限问题,蓝牙开发需要在AndroidManifest.xml文件中添加权限声明:

<!-- 蓝牙权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

为适配安卓6.0以及以上版本需要添加一个模糊定位的权限

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

手机权限管理中允许此权限,否则会出现无法搜索到设备的情况。

(二)打开蓝牙

在搜索设备之前需要询问打开手机蓝牙,其关键代码如下:

    //获取系统蓝牙适配器管理类
    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
            .getDefaultAdapter();

    // 询问打开蓝牙
    if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
    }
      // 申请打开蓝牙请求的回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "蓝牙已经开启", Toast.LENGTH_SHORT).show();
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "没有蓝牙权限", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

(三)搜索设备

本文主要针对BLE蓝牙开发,因此采用mBluetoothAdapter.startLeScan(LeScanCallback callback)方式扫描BLE蓝牙设备。调用方法如下:

mBluetoothAdapter.startLeScan(callback);
private LeScanCallback callback = new LeScanCallback() {

    @Override
    public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) {

        //device为扫描到的BLE设备
        if(device.getName() == "目标设备名称"){
            //获取目标设备
            targetDevice = device;
        }
    }
};

(四)连接设备

通过扫描BLE设备,根据设备名称区分出目标设备targetDevice,下一步实现与目标设备的连接。在连接设备之前要停止搜索蓝牙。

mBluetoothAdapter.stopLeScan(callback);

注 :停止搜索一般需要一定的时间来完成,最好调用停止搜索函数之后加以100ms的延时,保证系统能够完全停止搜索蓝牙设备。停止搜索之后启动连接过程。

BLE蓝牙的连接方法相对简单只需调用connectGatt方法,函数原型如下:

public BluetoothGatt connectGatt (Context context, boolean autoConnect, BluetoothGattCallback callback);

参数说明
返回值 BluetoothGatt: BLE蓝牙连接管理类,主要负责与设备进行通信。后续会进一步介绍该类。
boolean autoConnect:建议置为false,能够提升连接速度。
BluetoothGattCallback callback 连接回调,重要参数,BLE通信的核心部分。

(五)设备通信

与设备建立连接之后与设备通信,整个通信过程都是在BluetoothGattCallback的异步回调函数中完成。
BluetoothGattCallback中主要回调函数如下:

private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
    
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
        }
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic, int status) {
            
            super.onCharacteristicWrite(gatt, characteristic, status);

        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                BluetoothGattDescriptor descriptor, int status) {
        
            
        };

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {


        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic) {
            

        }
    };

上述几个回调函数是BLE开发中不可缺少的,每个函数的意义以及被调用的时机会在后续步骤中一一说明。

(1)等待设备连接成功

当调用targetdDevice.connectGatt(context, false, gattCallback)后系统会主动发起与BLE蓝牙设备的连接,若成功连接到设备将回调onConnectionStateChange方法,其处理过程如下:

@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                Log.e(TAG, "设备连接上 开始扫描服务");
                // 开始扫描服务,安卓蓝牙开发重要步骤之一
                mBluetoothGatt.discoverServices();
            }
            if (newState == BluetoothGatt.STATE_DISCONNECTED) {

                // 连接断开
                /*连接断开后的相应处理*/      
            }
};

判断newState == BluetoothGatt.STATE_CONNECTED表明此时已经成功连接到设备。

(2)开启扫描服务

mBluetoothGatt.discoverServices();

扫描BLE设备服务是安卓系统中关于BLE蓝牙开发的重要一步,一般在设备连接成功后调用,扫描到设备服务后回调onServicesDiscovered()函数,函数原型如下:。

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {

    private List<BluetoothGattService> servicesList;
    //获取服务列表
    servicesList = mBluetoothGatt.getServices();

}

BLE蓝牙协议下数据的通信方式采用BluetoothGattService、BluetoothGattCharacteristic和BluetoothGattDescriptor三个主要的类实现通信。
BluetoothGattService 简称服务,是构成BLE设备协议栈的组成单位,一个蓝牙设备协议栈一般由一个或者多个BluetoothGattService组成。
BluetoothGattCharacteristic 简称特征,一个服务包含一个或者多个特征,特征作为数据的基本单元。
一个BluetoothGattCharacteristic特征包含一个数据值和附加的关于特征的描述BluetoothGattDescriptor。
BluetoothGattDescriptor:用于描述特征的类,其同样包含一个value值。

(3)获取负责通信的BluetoothGattCharacteristic

BLE蓝牙开发主要有负责通信的BluetoothGattService完成的。当且称为通信服务。通信服务通过硬件工程师提供的UUID获取。获取方式如下:

BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("蓝牙模块提供的负责通信UUID字符串"));

通信服务中包含负责读写的BluetoothGattCharacteristic,且分别称为notifyCharacteristic和writeCharacteristic。其中notifyCharacteristic负责开启监听,也就是启动收数据的通道,writeCharacteristic负责写入数据。
具体操作方式如下:

  BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("蓝牙模块提供的负责通信服务UUID字符串"));
   // 例如形式如:49535343-fe7d-4ae5-8fa9-9fafd205e455
  notifyCharacteristic = service.getCharacteristic(UUID.fromString("notify uuid"));
  writeCharacteristic =  service.getCharacteristic(UUID.fromString("write uuid"));

(4)开启监听

开启监听,即建立与设备的通信的首发数据通道,BLE开发中只有当上位机成功开启监听后才能与下位机收发数据。开启监听的方式如下:

mBluetoothGatt.setCharacteristicNotification(notifyCharacteristic, true)
BluetoothGattDescriptor descriptor = characteristic
                            .getDescriptor(UUID
                                    .fromString
("00002902-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

若开启监听成功则会回调BluetoothGattCallback中的onDescriptorWrite()方法,处理方式如下:

@Override
public void onDescriptorWrite(BluetoothGatt gatt,
                BluetoothGattDescriptor descriptor, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
                
            //开启监听成功,可以像设备写入命令了
            Log.e(TAG, "开启监听成功");
        }
            
};

(5)写入数据

监听成功后通过向 writeCharacteristic写入数据实现与下位机的通信。写入方式如下:

//value为上位机向下位机发送的指令
writeCharacteristic.setValue(value);
mBluetoothGatt.writeCharacteristic(writeCharacteristic)

其中:value一般为Hex格式指令,其内容由设备通信的蓝牙通信协议规定。

(6)接收数据

若写入指令成功则回调BluetoothGattCallback中的onCharacteristicWrite()方法,说明将数据已经发送给下位机。

@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic, int status) {
            
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "发送成功");
            }   
            super.onCharacteristicWrite(gatt, characteristic, status);
}

若发送的数据符合通信协议,则下位机会向上位机回复相应的数据。发送的数据通过回调onCharacteristicChanged()方法获取,其处理方式如下:

@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic) {

            // value为设备发送的数据,根据数据协议进行解析
            byte[] value = characteristic.getValue();

}

通过向下位机发送指令获取下位机的回复数据,即可完成与设备的通信过程。

(六)断开连接

当与设备完成通信之后之后一定要断开与设备的连接。调用以下方法断开与设备的连接:

mBluetoothGatt.disconnect();
mBluetoothGatt.close();

通过以上六个主要步骤即可实现与设备的通信流程,BLE蓝牙开发流程相对固定,只需按照固定步骤执行即可。若按照上述流程扔不能完成整个通信过程,可以查看另外一篇文章安卓蓝牙开发填坑之路,看看是不是踩到坑了。



转载:https://www.jianshu.com/p/a27f3ca027e3

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值