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. Java中设计模式之工厂模式-4

    一.工厂模式由来 1)还没有工厂时代:假如还没有工业革命,如果一个客户要一款宝马车,一般的做法是客户去创建一款宝马车,然后拿来用. 2)简单工厂模式:后来出现工业革命.用户不用去创建宝马车.因为客户有 ...

  2. ssh框架整合之登录以及增删改查

    1.首先阐述一下我用得开发工具,myeclipse2017+oracle,所以我的基本配置步骤可能不一样,下面我用几张图来详解我的开发步骤. ---1先配置structs (Target 选择apac ...

  3. mysql之 mysql 5.6不停机主从搭建(一主一从)

    环境说明:版本 version 5.6.25-log 主库ip: 10.219.24.25从库ip:10.219.24.22os 版本: centos 6.7已安装热备软件:xtrabackup 防火 ...

  4. SVN·最新使用教程总结

    SVN简介: 为什么要使用SVN? 程序员在编写程序的过程中,每个程序员都会生成很多不同的版本,这就需要程序员有效的管理代码,在需要的时候可以迅速,准确取出相应的版本. Subversion是什么? ...

  5. 借用mysql 或者其他数据库 处理MSSQL 2016前处理导入特殊字符

    MSSQL 2016支持了utf8编码的文件,之前处理比较麻烦的bcp 方式导入特殊字符一下子就方便了. 但是之前的版本,处理起来还是有一点麻烦.这次处理使用的数据库版本是sql server 201 ...

  6. JavaScript数组基础及实例

    js数组 和var i=1;这样的简单存储一样是js中的一种数据结构,是专门用来存储多个数据的一种数据结构. 摘:数组是一组数据的集合,其表现形式就是内存中的一段连续的内存地址,数组名称其实就是连续内 ...

  7. Python中如何调用Linux命令

    一.使用os模块 In [1]: import os #导入os模块 In [2]: os.system('ls') anaconda-ks.cfg epel-release-7-5.noarch.r ...

  8. 小试牛刀JavaScript鼠标事件

    鼠标事件练习1 当鼠标点击网页某个单元格的时候,其他的单元格颜色不变,只有被点击的单元格颜色发生变化 <style type="text/css"> *{ margin ...

  9. Xcode9新特性介绍-中文篇

    背景: Xcode 9 新特性介绍: 1.官方原文介绍链接 2.Xcode9 be ta 2 官方下载链接 本文为官方介绍翻译而来,布局排版等都是按照官方布局来的. 与原文相比,排版上基本还是熟悉的配 ...

  10. php中的命名空间

    a.php <?php namespace a\b; class Apple{ function get_info(){ echo 'aaa'.'<br/>'; } } ?> ...