Android BLE 连接及数据传输详解

本文将展开对蓝牙低功耗从扫描蓝牙设备,建立连接到蓝牙数据通信的详细介绍,以及详细介绍GATT Profile(Generic Attribute Profile,通用属性协议)的组成结构。

权限和feature

和经典蓝牙一样,使用低功耗蓝牙,需要声明BLUETOOTH权限,如果需要扫描设备或者操作蓝牙设置,则还需要BLUETOOTH_ADMIN权限:

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

除了蓝牙权限外,如果需要BLE feature则还需要声明uses-feature:

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

当required为true时,则应用只能在支持BLE的Android设备上安装运行;required为false时,Android设备均可正常安装运行,需要在代码中判断设备是否支持BLE feature:

if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
  Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
  finish();
}
创建BLE

在应用可以通过 BLE 交互之前, 你需要验证设备是否支持 BLE 功能, 如果支持, 确定它是可以使用的. 这个检查只有在 下面的配置 设置为 false 时才是必须的。

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

获取蓝牙适配器(BluetoothAdapter)

所有的蓝牙活动都需要 BluetoothAdapter, BluetoothAdapter 代表了设备本身的蓝牙适配器 (蓝牙无线设备). 整个系统中只有一个 蓝牙适配器, 应用可以使用 BluetoothAdapter 对象与 蓝牙适配器硬件进行交互.

// Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
打开蓝牙功能

为了保证 蓝牙功能是打开的, 调用 BluetoothAdapter 的 isEnable() 方法, 检查蓝牙在当前是否可用. 如果返回 false, 说明当前蓝牙不可用.

// 确认当前设备的蓝牙是否可用,   
// 如果不可用, 弹出一个对话框, 请求打开设备的蓝牙模块  
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {  
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);  
}  
查找设备

搜索 BLE 设备, 调用 BluetoothAdapter 的 startLeScan() 方法, 该方法需要一个 BluetoothAdapter.LeScanCallback 类型的参数. 你必须实现这个 LeScanCallback 接口, 因为 BLE 蓝牙设备扫描结果在这个接口中返回.蓝牙搜索是一个耗电的操作,因此蓝牙搜索提供了两种搜索模式:
中断搜索:一搜索到设备就中断搜索
不循环搜索:给搜索设置一个合适的扫描周期

扫描设备:

private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {

                public void run() {
                    isScanned = false;
                    refreshLayout.setRefreshing(false);
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);

            isScanned = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            if (refreshLayout.isRefreshing()){
                refreshLayout.setRefreshing(false);
            }
            isScanned = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }

回调代码:

 private final LeScanCallback mLeScanCallback = new LeScanCallback() {

        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (!devices.contains(device)){
                        devices.add(device);
                        adapter.notifyDataSetChanged();
                    }

                }
            });
        }
    };
查找特定设备

查找特定类型的外围设备, 可以调用下面的方法, 这个方法需要提供一个 UUID 对象数组, 这个 UUID 数组是 APP 支持的 GATT 服务的特殊标识.

startLeScan(UUID[], BluetoothAdapter.LeScanCallback)

连接到GATT服务

调用 BluetoothDevice 的 connectGatt() 方法可以连接到 BLE 设备的 GATT 服务. 参数一 Context 上下文对象, 参数二 boolean autoConnect 是否自动连接扫描到的蓝牙设备, 参数三 BluetoothGattCallback 接口实现类.

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

GATT数据交互

这段代码的本质就是 BLE 设备的 GATT 服务 与 Android 的 BLE API 进行交流. 当一个特定的回调被触发, 它调用适当的 broadcastUpdate() 帮助方法, 将其当做一个 Action 操作传递出去.

/**
     * Implements callback methods for GATT events that the app cares about.
     * For example,connection change and services discovered.
     */
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }else if (newState == BluetoothProfile.STATE_CONNECTING){
                intentAction = ACTION_GATT_CONNECTING;
                Log.i(TAG, "connecting from GATT server.");
                broadcastUpdate(intentAction);
            }else{
                intentAction = ACTION_GATT_DISCONNECTING;
                Log.i(TAG, "Disconnecting from GATT server.");
                broadcastUpdate(intentAction);
            }
        }
读取 BLE 属性

到了这里我就要详细的讲解一下BLE GATT PROFILE的组织结构了。每个蓝牙设备都有一个Profile(就把这个Profile想象成是一个蓝牙模块),每个Profile有多个service(服务)如电量信息服务、系统信息服务等,每个service有多个Characteristic(特征),每个特征里面包括属性(properties)和值(value)和若干个descriptor(描述符)。我们刚才提到的service和characteristic,都需要一个唯一的uuid来标识,如图:
[图片上传失败...(image-89e748-1514968778904)]
Android 应用连接到了 设备中的 GATT 服务, 并且发现了 各种服务 (特征集合), 可以读写其中的属性,遍历服务 (特征集合) 和 特征, 将其展示在 UI 界面中.

 // 遍历 GATT 服务  
        for (BluetoothGattService gattService : gattServices) {  
            HashMap<String, String> currentServiceData =  
                    new HashMap<String, String>();  
            uuid = gattService.getUuid().toString();  
            currentServiceData.put(  
                    LIST_NAME, SampleGattAttributes.  
                            lookup(uuid, unknownServiceString));  
            currentServiceData.put(LIST_UUID, uuid);  
            gattServiceData.add(currentServiceData);  
  
            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =  
                    new ArrayList<HashMap<String, String>>();  
                      
            // 获取服务中的特征集合  
            List<BluetoothGattCharacteristic> gattCharacteristics =  
                    gattService.getCharacteristics();  
            ArrayList<BluetoothGattCharacteristic> charas =  
                    new ArrayList<BluetoothGattCharacteristic>();  
                      
           // 循环遍历特征集合  
            for (BluetoothGattCharacteristic gattCharacteristic :  
                    gattCharacteristics) {  
                charas.add(gattCharacteristic);  
                HashMap<String, String> currentCharaData =  
                        new HashMap<String, String>();  
                uuid = gattCharacteristic.getUuid().toString();  
                currentCharaData.put(  
                        LIST_NAME, SampleGattAttributes.lookup(uuid,  
                                unknownCharaString));  
                currentCharaData.put(LIST_UUID, uuid);  
                gattCharacteristicGroupData.add(currentCharaData);  
            }  
            mGattCharacteristics.add(charas);  
            gattCharacteristicData.add(gattCharacteristicGroupData);  
         }  
接收GATT通知

当 BLE 设备中的一些特殊的特征改变, 需要通知与之连接的 Android BLE 应用,使用 setCharacteristicNotification() 方法为特征设置通知.

private BluetoothGatt mBluetoothGatt;  
BluetoothGattCharacteristic characteristic;  
boolean enabled;  
...  
// 设置是否监听某个特征改变  
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);  
...  
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(  
        UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));  
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);  
mBluetoothGatt.writeDescriptor(descriptor);  

一旦特征开启了改变通知监听, 如果特性发生了改变, 就会回调 BluetoothGattCallback 接口中的 onCharacteristicChanged() 方法.

@Override  
// 特性通知  
public void onCharacteristicChanged(BluetoothGatt gatt,  
        BluetoothGattCharacteristic characteristic) {  
    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);  
}  
关闭APP中的BLE连接

一旦结束了 BLE 设备的使用, 调用 BluetoothGatt 的 close() 方法, 关闭 BLE 连接, 释放相关的资源.

public void close() {  
    if (mBluetoothGatt == null) {  
        return;  
    }  
    mBluetoothGatt.close();  
    mBluetoothGatt = null;  
}  

完整项目链接,访问我的开源中国账号osgit

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容