蓝牙低能量概述

Android 4.3(API级别18)引入了内置平台支持蓝牙低功耗(BLE)的核心角色,并提供应用程序可用于发现设备,查询服务和传输信息的API。
常见用例包括以下内容:

  • 在附近设备之间传输少量数据。
  • 与Google Beacons等接近传感器进行交互,根据用户的当前位置为用户提供定制体验。

与经典蓝牙相比,蓝牙低功耗(BLE)旨在提供显着降低的功耗。 这允许Android应用程序与具有更严格电源要求的BLE设备通信,例如接近传感器,心率监视器和健身设备。

关键术语和概念

以下是关键BLE术语和概念的摘要:

  • 通用属性配置文件(GATT) - GATT配置文件是用于在BLE链路上发送和接收称为“属性”的短数据的通用规范。 目前所有低能耗应用配置文件均基于GATT。
  • Bluetooth SIG为低能耗设备定义了许多配置文件。 配置文件是设备在特定应用程序中的工作方式的规范。 请注意,设备可以实现多个配置文件。 例如,设备可以包含心率监测器和电池水平检测器。
  • 属性协议(ATT)-GATT建立在属性协议(ATT)之上。 这也称为GATT / ATT。 ATT经过优化,可在BLE设备上运行。 为此,它使用尽可能少的字节。 每个属性由通用唯一标识符(UUID)唯一标识,UUID是用于唯一标识信息的字符串ID的标准化128位格式。 ATT传输的属性被格式化为特征和服务。
  • 特征 - 特征包含描述特征值的单个值和0-n描述符。 特征可以被认为是类型,类似于类。
  • 描述符 - 描述符是定义描述特征值的属性。 例如,描述符可以指定人类可读的描述,特征值的可接受范围,或特征值特定的度量单位。
  • 服务 - 服务是一系列特征。 例如,您可以使用名为“心率监测器”的服务,其中包括“心率测量”等特征。 您可以在bluetooth.org上找到基于GATT的现有配置文件和服务的列表。
角色和责任

以下是Android设备与BLE设备交互时应用的角色和职责:

  • 中央与外围。 这适用于BLE连接本身。 中心角色的设备扫描,寻找广告,外围角色的设备制作广告。
  • GATT服务器与GATT客户端。 这确定了两个设备建立连接后如何相互通信。

要了解这种区别,请假设您拥有一部Android手机和一台BLE设备的活动跟踪器。手机支持中心角色;活动跟踪器支持外围角色(为了建立一个BLE连接,你需要一个 - 两个只支持外围设备无法相互通信的东西,也不能只支持两个中心的东西)。
一旦电话和活动跟踪器建立了连接,他们就开始将GATT元数据相互转移。根据它们传输的数据类型,一个或另一个可能充当服务器。例如,如果活动跟踪器想要将传感器数据报告给电话,则活动跟踪器充当服务器可能是有意义的。如果活动跟踪器想要从手机接收更新,那么手机充当服务器可能是有意义的。
在本文档中使用的示例中,Android应用程序(在Android设备上运行)是GATT客户端。该应用程序从GATT服务器获取数据,GATT服务器是支持心率配置文件的BLE心率监测器。但您也可以将Android应用设计为扮演GATT服务器角色。有关更多信息,请参阅BluetoothGattServer。

BLE权限

要在您的应用程序中使用蓝牙功能,您必须声明蓝牙权限BLUETOOTH。 您需要此权限才能执行任何蓝牙通信,例如请求连接,接受连接和传输数据。
如果您希望应用程序启动设备发现或操作蓝牙设置,则还必须声明BLUETOOTH_ADMIN权限。 注意:如果使用BLUETOOTH_ADMIN权限,则还必须具有BLUETOOTH权限。
在应用程序清单文件中声明蓝牙权限。 例如:

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

如果您要声明您的应用仅适用于支持BLE的设备,请在应用清单中包含以下内容:

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

但是,如果您希望将应用程序提供给不支持BLE的设备,您仍应将此元素包含在应用程序的清单中,但必须设置required =“false”。 然后在运行时,您可以使用PackageManager.hasSystemFeature()确定BLE可用性:

// Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    finish();
}

注意:LE Beacons通常与位置相关联。 要使用BluetoothLeScanner,您必须通过在应用程序的清单文件中声明ACCESS_COARSE_LOCATION或ACCESS_FINE_LOCATION权限来请求用户的权限。 没有这些权限,扫描将不会返回任何结果。

设置BLE

在您的应用程序可以通过BLE进行通信之前,您需要验证设备是否支持BLE,如果是,请确保它已启用。 请注意,仅当<uses-feature ... />设置为false时才需要进行此检查。
如果不支持BLE,则应优雅地禁用任何BLE功能。 如果BLE受支持但已禁用,则您可以请求用户启用蓝牙而无需离开您的应用程序。 使用BluetoothAdapter,可以分两步完成此设置。

  • 获取BluetoothAdapter
    任何和所有蓝牙活动都需要BluetoothAdapter。 BluetoothAdapter代表设备自己的蓝牙适配器(蓝牙无线电)。 整个系统都有一个蓝牙适配器,您的应用程序可以使用此对象与其进行交互。 下面的代码段显示了如何获取适配器。 请注意,此方法使用getSystemService()返回BluetoothManager的实例,然后使用该实例获取适配器。 Android 4.3(API Level 18)介绍了BluetoothManager:
private BluetoothAdapter bluetoothAdapter;
...
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
  • 启用蓝牙
    接下来,您需要确保启用蓝牙。 调用isEnabled()检查当前是否启用了蓝牙。 如果此方法返回false,则禁用蓝牙。 以下代码段会检查是否已启用蓝牙。 如果不是,则代码段会显示错误提示用户转到“设置”以启用蓝牙:
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

注意:传递给startActivityForResult(android.content.Intent,int)的REQUEST_ENABLE_BT常量是一个本地定义的整数(必须大于0),系统会在你的onActivityResult(int,int,android.content)中传回给你。 Intent)实现为requestCode参数。

找到BLE设备

要查找BLE设备,请使用startLeScan()方法。 此方法将BluetoothAdapter.LeScanCallback作为参数。 您必须实现此回调,因为这是返回扫描结果的方式。 由于扫描是电池密集型的,因此您应遵守以下准则:

  • 找到所需设备后,请立即停止扫描。
  • 切勿扫描循环,并设置扫描时间限制。 之前可用的设备可能已超出范围,并继续扫描耗尽电池。

以下代码段显示了如何启动和停止扫描:

/**
 * Activity for scanning and displaying available BLE devices.
 */
public class DeviceScanActivity extends ListActivity {

    private BluetoothAdapter bluetoothAdapter;
    private boolean mScanning;
    private Handler handler;

    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    ...
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    bluetoothAdapter.stopLeScan(leScanCallback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            bluetoothAdapter.startLeScan(leScanCallback);
        } else {
            mScanning = false;
            bluetoothAdapter.stopLeScan(leScanCallback);
        }
        ...
    }
...
}

如果您只想扫描特定类型的外围设备,可以调用startLeScan(UUID [],BluetoothAdapter.LeScanCallback),提供一组UUID对象,指定您的应用支持的GATT服务。
以下是BluetoothAdapter.LeScanCallback的实现,它是用于提供BLE扫描结果的接口:

private LeDeviceListAdapter leDeviceListAdapter;
...
// Device scan callback.
private BluetoothAdapter.LeScanCallback leScanCallback =
        new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi,
            byte[] scanRecord) {
        runOnUiThread(new Runnable() {
           @Override
           public void run() {
               leDeviceListAdapter.addDevice(device);
               leDeviceListAdapter.notifyDataSetChanged();
           }
       });
   }
};

注意:您只能扫描蓝牙LE设备或扫描经典蓝牙设备,如蓝牙中所述。 您无法同时扫描蓝牙LE和传统设备。

连接到GATT服务器

与BLE设备交互的第一步是连接到它 - 更具体地说,连接到设备上的GATT服务器。 要连接到BLE设备上的GATT服务器,请使用connectGatt()方法。 此方法有三个参数:一个Context对象,autoConnect(指示是否在可用时自动连接到BLE设备的布尔值),以及对BluetoothGattCallback的引用:

bluetoothGatt = device.connectGatt(this, false, gattCallback);

这将连接到BLE设备托管的GATT服务器,并返回一个BluetoothGatt实例,然后您可以使用该实例执行GATT客户端操作。 呼叫者(Android应用)是GATT客户端。 BluetoothGattCallback用于向客户端提供结果,例如连接状态,以及任何进一步的GATT客户端操作。
在此示例中,BLE应用程序提供活动(DeviceControlActivity)以连接,显示数据和显示设备支持的GATT服务和特征。 根据用户输入,此活动与名为BluetoothLeService的服务进行通信,该服务通过Android BLE API与BLE设备进行交互:

// A service that interacts with the BLE device via the Android BLE API.
public class BluetoothLeService extends Service {
    private final static String TAG = BluetoothLeService.class.getSimpleName();

    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private String bluetoothDeviceAddress;
    private BluetoothGatt bluetoothGatt;
    private int connectionState = STATE_DISCONNECTED;

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;

    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA =
            "com.example.bluetooth.le.EXTRA_DATA";

    public final static UUID UUID_HEART_RATE_MEASUREMENT =
            UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);

    // Various callback methods defined by the BLE API.
    private final BluetoothGattCallback gattCallback =
            new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                connectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" +
                        bluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                connectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        }

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic,
                int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }
     ...
    };
...
}

当触发特定回调时,它会调用相应的broadcastUpdate()辅助方法并向其传递操作。 请注意,本节中的数据解析是根据蓝牙心率测量配置文件规范执行的:

private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

private void broadcastUpdate(final String action,
                             final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile. Data
    // parsing is carried out as per profile specifications.
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for(byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" +
                    stringBuilder.toString());
        }
    }
    sendBroadcast(intent);
}

回到DeviceControlActivity,这些事件由BroadcastReceiver处理:

// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a
// result of read or notification operations.
private final BroadcastReceiver gattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            connected = true;
            updateConnectionState(R.string.connected);
            invalidateOptionsMenu();
        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
            connected = false;
            updateConnectionState(R.string.disconnected);
            invalidateOptionsMenu();
            clearUI();
        } else if (BluetoothLeService.
                ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
            // Show all the supported services and characteristics on the
            // user interface.
            displayGattServices(bluetoothLeService.getSupportedGattServices());
        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

读BLE属性

一旦您的Android应用程序连接到GATT服务器并发现了服务,它就可以在支持的位置读取和写入属性。 例如,此代码段迭代服务器的服务和特征,并在UI中显示它们:


public class DeviceControlActivity extends Activity {
    ...
    // Demonstrates how to iterate through the supported GATT
    // Services/Characteristics.
    // In this sample, we populate the data structure that is bound to the
    // ExpandableListView on the UI.
    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;
        String uuid = null;
        String unknownServiceString = getResources().
                getString(R.string.unknown_service);
        String unknownCharaString = getResources().
                getString(R.string.unknown_characteristic);
        ArrayList<HashMap<String, String>> gattServiceData =
                new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
                = new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics =
                new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // Loops through available GATT Services.
        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>();
           // Loops through available Characteristics.
            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应用程序通常会要求在设备上的特定特征发生变化时收到通知。 此代码段显示如何使用setCharacteristicNotification()方法设置特征的通知:

private BluetoothGatt bluetoothGatt;
BluetoothGattCharacteristic characteristic;
boolean enabled;
...
bluetoothGatt.setCharacteristicNotification(characteristic, enabled);
...
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
        UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
bluetoothGatt.writeDescriptor(descriptor);

为特性启用通知后,如果远程设备上的特性发生更改,则会触发onCharacteristicChanged()回调:

@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
        BluetoothGattCharacteristic characteristic) {
    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}

关闭客户端应用程序

一旦您的应用程序使用完BLE设备,它应该调用close(),以便系统可以适当地释放资源:

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

推荐阅读更多精彩内容