Android Bluetooth Low Energy

Android 低功耗蓝牙简介
2016-4-18

Android4.3(API 18)介绍了平台支持的低功耗蓝牙,app可用于发现设备,检索服务和读写特性(characteristics)。相比于传统蓝牙,低功耗蓝牙(BLE)消耗更少。它能够连接到外围的BLE设备,比如距离感应器、心率感应器、健康设备等等。

关键词和概念

  • Generic Attribute Profile (GATT)
    GATT模式是通过BLE连接发送接收“attributes”短数据的通用模式。目前所有的低功耗应用都基于GATT。
    蓝牙SIG定义了许多的低功耗设备模式。一个配置(profile)是设备在特定应用下的工作方式。请注意,一个设备可以实现不止一个配置。比如,一个设备可以同时包含心率感应器和一个电量检测器。

  • Attribute Protocol (ATT)
    GATT建立在属性协议(ATT)之上。这也可以看为GATT/ATT。ATT有针对BLE设备的优化。ATT使用尽可能少的字节。每个特性(attributes)都由一个UUID来标示。UUID(Universally Unique Identifier)是一个标准128位的字符串ID,用于识别单一的信息。ATT以服务(services)和属性(characteristics)来传送特性(attributes)。

  • Characteristic
    一个characteristic包含一个单独的值和0~n个描述值的descriptor。一个characteristic可以被当做是类的类型。

  • Descriptor
    用于描述characteristic的值。比如一个描述器可能指定一个可读的描述语句。

  • Service
    service是characteristics的集合。比如你可以有一个service叫做“Heart Rate Monitor”,里面包含多个characteristic,比如“heart rate measurement”。

角色和职责

  • 中心设备与外围设备。中心设备搜索寻找信号,外围设备发送信号。
  • GATT服务端与GATT客户端。这决定了2个设备建立连接后如何通信。

假设有一个Android手机和一个BLE设备。手机扮演中心角色,设备扮演外围角色。
手机和外设建立连接后,他们相互传送GATT元数据(Metadata)。由传送数据的类型来决定谁做主机。比如,外设想要报告传感器数据给手机,那么外设来做服务端。如果外设要从手机接收更新信息,那么手机来做服务端。

BLE Permissions

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

如果要声明APP仅适用于BLE设备,在manifest中写

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

上面的代码中true改为false,就是不支持BLE设备

// 检查这台设备是否支持BLE
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, “本机不支持BLE”, Toast.LENGTH_SHORT).show();
    finish();
}

设置BLE

1.获取BluetoothAdapter

蓝牙app都需要BluetoothAdapter。

// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

2.激活蓝牙

private BluetoothAdapter mBluetoothAdapter;
...
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

寻找BLE设备

DeviceScanActivity.java
DeviceControlActivity.java
BluetoothLeService.java

DeviceScanActivity负责搜索BLE设备;选定设备后启动BluetoothLeService,并且所有BLE操作都在这里进行;
DeviceControlActivity提供UI,从BluetoothLeService发来的信息在这里显示

调用startLeScan(),当然现在有替代的方法了

请注意:

  • 一旦找到需要的设备,马上停止搜索

  • 不要循环搜索,并设置一个时间限制。循环搜索很耗电。

以下代码是启动和停止搜索功能

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

    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    // 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.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        ...
    }
...
}

如果要搜索特定类型的外围设备,使用 startLeScan(UUID[], BluetoothAdapter.LeScanCallback)
提供一组特定的GATT services UUID对象

下面是BluetoothAdapter.LeScanCallback的实现

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

请注意,不能同时搜索BLE设备和传统蓝牙设备。

连接到GATT服务端

在GATT客户端进行这个操作

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
// mGattCallback在上面写好了

下面是一个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 mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;
    private int mConnectionState = 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 mGattCallback =
            new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = 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);
            }
        }
     ...
    };
...
}

这里值得注意的是,连接上之后不要马上进行读写characteristic的操作。要等onServicesDiscovered执行后再读写命令。

下面是发送广播的辅助方法

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中接收处理

// 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 mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            mConnected = true;
            updateConnectionState(R.string.connected);
            invalidateOptionsMenu();
        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
            mConnected = 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(mBluetoothLeService.getSupportedGattServices());
        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

读取BLE属性

Android APP连接上BLE服务端后,就可以发现服务,并能读写属性值。
下面是一个读属性的例子,它将服务端所有的属性都列出来

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提示

当设备上特定的characteristic改变时,app能够接收到提示

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);
@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
        BluetoothGattCharacteristic characteristic) {
    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}

关闭客户端APP

用完BLE设备后,调用close方法来关闭

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

Android-Bluetooth Low Energy(BLE)的更多相关文章

  1. Android Bluetooth Low Energy (BLE)简单方便的蓝牙开源库——EasyBLE

    源码传送门 最新版本 功能 支持多设备同时连接 支持广播包解析 支持连接同时配对 支持搜索系统已连接设备 支持搜索器设置 支持自定义搜索过滤条件 支持自动重连.最大重连次数限制.直接重连或搜索到设备再 ...

  2. Android bluetooth low energy (ble) writeCharacteristic delay callback

    I am implementing a application on Android using BLE Api (SDK 18), and I have a issue that the trans ...

  3. Android使用BLE(低功耗蓝牙,Bluetooth Low Energy)

    背景 在学习BLE的过程中,积累了一些心得的DEMO,放到Github,形成本文.感兴趣的同学可以下载到源代码. github: https://github.com/vir56k/bluetooth ...

  4. 基于蓝牙4.0(Bluetooth Low Energy)胎压监测方案设计

    基于一种新的蓝牙技术——蓝牙4.0(Bluetooth Low Energy)新型的胎压监测系统(TPMS)的设计方案.鉴于蓝牙4.0(Bluetooth Low Energy)的低成本.低功耗.高稳 ...

  5. How to Implement Bluetooth Low Energy (BLE) in Ice Cream Sandwich

    ShareThis - By Vikas Verma Bluetooth low energy (BLE) is a feature of Bluetooth 4.0 wireless radio t ...

  6. Android低功耗蓝牙(BLE)使用详解

    代码地址如下:http://www.demodashi.com/demo/13390.html 与普通蓝牙相比,低功耗蓝牙显著降低了能量消耗,允许Android应用程序与具有更严格电源要求的BLE设备 ...

  7. Bluefruit LE Sniffer - Bluetooth Low Energy (BLE 4.0) - nRF51822 驱动安装及使用

    BLE Sniffer https://www.adafruit.com/product/2269 Bluefruit LE Sniffer - Bluetooth Low Energy (BLE 4 ...

  8. Android源码分析(六)-----蓝牙Bluetooth源码目录分析

    一 :Bluetooth 的设置应用 packages\apps\Settings\src\com\android\settings\bluetooth* 蓝牙设置应用及设置参数,蓝牙状态,蓝牙设备等 ...

  9. 物联网安全拔“牙”实战——低功耗蓝牙(BLE)初探

    物联网安全拔“牙”实战——低功耗蓝牙(BLE)初探 唐朝实验室 · 2015/10/30 10:22 Author: FengGou 0x00 目录 0x00 目录 0x01 前言 0x02 BLE概 ...

随机推荐

  1. 热部署环境下,dubbo序列化的bug和优化

    一.问题的发现与解决 (1)     在热部署下,使用dubbo的序列化一个pojo对象,反序列化时报错:ClassNotFoundException. 最后发现原因是我们的框架选择使用了java序列 ...

  2. C语言指针声明探秘

    C语言指针声明探秘

  3. 对 dotweb 框架进行统一的自定义错误处理

    助移动端的增长,如今 RESTful 风格的 API 已经十分流行, 用各种语言去写后端 API 都有很成熟方便的方案,用 golang 写后端 API 更是生产力的代表, 你可以用不输 python ...

  4. [UWP]用Shape做动画

    相对于WPF/Silverlight,UWP的动画系统可以说有大幅提高,不过本文无意深入讨论这些动画API,本文将介绍使用Shape做一些进度.等待方面的动画,除此之外也会介绍一些相关技巧. 1. 使 ...

  5. vue+websocket+express+mongodb实战项目(实时聊天)(二)

    原项目地址:[ vue+websocket+express+mongodb实战项目(实时聊天)(一)][http://blog.csdn.net/blueblueskyhua/article/deta ...

  6. spring4 之 helloworld

    1.从官网下载相关JAR包 spring-framework-4.2.1.RELEASE-dist(下载地址:http://maven.springframework.org/release/org/ ...

  7. nmon用法

    一.简介 nmon是一个简单的性能监测工具,可以监测CPU.内存.网络等的使用情况.它是一个系统监视.调优.性能测试工具,它能一次性提供大量性能相关的信息. 二.安装与执行 下载地址:http://n ...

  8. 今天学习js做了些总结,分享给大家

    一.1.javascript的作用   是基于对象和事件驱动的语言,应用于客户端   基于对象:提供好了很多对象,可以直接拿过来使用,不需要创建   事件驱动: html做网站静态效果,javascr ...

  9. OpenCV探索之路(十七):Mat和IplImage访问每个像素的方法总结

    在opencv的编程中,遍历访问图像元素是经常遇到的操作,掌握其方法非常重要,无论是Mat类的像素访问,还是IplImage结构体的访问的方法,都必须扎实掌握,毕竟,图像处理本质上就是对像素的各种操作 ...

  10. oracle创建数据库表空间 用户 授权 导入 导出数据库

    windows下可以使用向导一步一步创建数据库,注意编码. windows连接到某一个数据库实例(不然会默认到一个实例下面):set ORACLE_SID=TEST --登录开始创建表空间及可以操作的 ...