Android 蓝牙4.0低功耗(BLE)官方详解(译)

声明:转载请注明出处http://www.jianshu.com/p/54bc88207050

Android 4.3(API level 18)引入了蓝牙低功耗(BLE)核心功能,并提供了API可供app来搜索设备,查询服务以及传输信息。

蓝牙低功耗通常用于以下几个方面:

  • 在两个相近的设备之间传输少量数据。
  • 与距离传感器进行交互,比如Google Beacons。这样可以基于当前位置来定制用户个性化体验。

相比经典蓝牙,蓝牙低功耗(BLE)可以显著减少电量消耗。这使得Android应用可以与对电量有着更严格限制的设备通信,比如位置传感器,心率监视器,以及健身设备。

关键术语和概念

以下是对BLE关键术语和概念的总结:

  • Generic Attribute Profile (GATT)--GATT profile是发送和接收少量数据的一种通用规范,正如大家知道的在BLE连接上的“attributes”。当前所有的低功耗应用profile都是基于GATT。

    • 蓝牙技术联盟为低功耗设备定义了很多profile。profile就是指定设备在特定的应用中如何工作的一种规范 。举个例子,一个设备可以包含一个心率监视器和一个电量状态监测器。
  • Attribute Protocol (ATT)--GATT是建立在ATT的基础之上。所以也称之为GATT/ATT。ATT在BLE设备上运行经过了优化,因此,它会尽可能使用更少的字节数组。每个属性通过UUID来唯一确定,UUID是一种128位的标准化格式字符串ID来标识信息的唯一性。属性会被格式化为特征(characteristics )与服务(services)后通过ATT来传输。

  • 特征(Characteristic)--一个特征包含了一个单独的值和0-n个描述符(descriptors ,用来描述特征的值)。一个特征可以看做是一种类型,类似一个class。

  • 描述符(Descriptor)--描述符定义了属性用来描述特征值。比如,描述符可以是人们可读的描述语句,可以是特征值得可接受范围,或者是特征值的测量单位。

  • 服务(Service)--服务是特征的集合。比如,你有一个叫做‘心率监视器’的服务,在这个服务里包含一个“心率测量”的特征。你可以在bluetooth.org上查看一系列基于GATT的profile与服务。

角色与职责

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

  • 中心 vs 外设。这适用于BLE自身的连接。中心设备扫描,搜索广告,外设发送广告。
  • GATT服务 vs GATT客户端。这决定了两个设备之间如何通信一旦他们建立了连接。

为了更好的理解不同,想象下假如你有一个Android手机与一个具有蓝牙低功耗的活动追踪器设备。手机支持中心角色;活动追踪器支持外设角色(为了建立连接两个设备必须是不同的角色,不能同时为同一个角色)。
一旦手机与蓝牙设备建立了连接。他们就会传输GATT媒体数据到另一设备。根据传输的数据,它们其中一个需要作为服务端。比如,如果活动追踪设备想要上传传感数据到手机,那么该活动追踪器就作为服务端。如果活动追踪设备想要接收手机传来的数据,那么手机就是服务端。

在文章中举的例子中,Android应用是GATT客户端。app从GATT服务端获取数据,这个服务也就是支持 心率Profile 的心率监视器。当然你也可以是你的Android app扮演服务端角色。可以查阅BluetoothGattServer获取更多信息。

BLE权限

为了在你的应用中使用蓝牙,你需要申明蓝牙权限BLUETOOTH。你需要这个权限来实现任何的蓝牙通信,比如请求连接,接收连接以及传输数据。

如果你想是你的app开启设备搜索以及管理蓝牙设置,你必须申明BLUETOOTH_ADMIN权限。注意:如果你申明了BLUETOOTH_ADMIN权限,那么你必须同时申明BLUETOOTH权限。

在你的manifest文件里申明权限,如下:

<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的设备上使用你的app,你也需要添加上面的申明,只是需要将required设为false。这样你可以在运行时通过调用 PackageManager.hasSystemFeature()来判断该设备是否支持BLE。

// 用以下方式来判断设备是否支持BLE,从而选择性的禁用BLE相关特性
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    finish();
}

注意:BLE经常与位置有联系。所以为了不带过滤器的使用
BluetoothLeScanner,你必须申明ACCESS_COARSE_LOCATION或者ACCESS_FINE_LOCATION权限来访问用户的位置信息。如果没有这些权限,那么扫描将会没有任何结果。

设置BLE

在你的应用使用BLE通信之前,你需要确认你的设备是否支持BLE,如果支持,那么确保蓝牙是打开的。注意这个判断只有在<uses-feature/>标签设为false的时候才是必须的。

如果设备不支持BLE,那么你应该优雅的禁用任何蓝牙功能。如果支持BLE,但还没开启的话,你可以让用户在应用内打开蓝牙。你可以使用BluetoothAdapter通过以下两步来完成该操作:
1.获取BluetoothAdapter
BluetoothAdapter对于所有蓝牙活动都是必须。BluetoothAdapter代表设备自己的蓝牙适配器。整个设备系统中只有一个蓝牙适配器,你的应用可以用这个对象来和它交互。以下代码片展示了如何获取这个适配器。注意这里使用getSystemService()来返回一个BluetoothManager实例,这可以用来获取适配器。Android 4.3(API 18)才引入的BluetoothManager:

private BluetoothAdapter mBluetoothAdapter;
...
// 初始化蓝牙适配器
final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

2.开启蓝牙
接下来,你需要确认蓝牙是否打开。调用
isEnabled()方法来确认当前蓝牙是否打开。如果返回false,则蓝牙未开启。下面的代码片判断蓝牙是否开启。如果没有,则提示用户开启蓝牙:

// 确保设备支持蓝牙,并已开启,如果未开启,则显示一个弹窗来获取用户权限打开蓝牙
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

注意:传入startActivityForResult的常量REQUEST_ENABLE_BT 是定义在本地的int类型,系统会将这个常量作为requestCode参数回传到onActivityResult方法。

搜索BLE设备

你可以使用 startLeScan()方法来搜索设备。这个方法需要传入一个回调参数BluetoothAdapter.LeScanCallback。你必须实现这个回调接口,因为搜索结果会通过这个回调返回。由于扫描是耗电的,你需要遵循以下准则:

  • 当搜索到你想要的设备就应该停止扫描
  • 不能无限的扫描下去,需要给扫描做个时间限制。之前可以访问的设备可能超出距离限制,继续扫描只会消耗电量。

以下代码片展示了如何开始以及结束扫描:

/**
 * 一个用于扫描的Activity并展示搜到的设备
 */
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)方法,需要传入你app支持的特定GATT服务的UUID对象数组。
以下是 BluetoothAdapter.LeScanCallback接口实现,用来返回扫描结果:

private LeDeviceListAdapter mLeDeviceListAdapter;
...
// 设备扫描回调
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();
           }
       });
   }
};

注意:正如在文章 Bluetooth中描述的,你只能扫描BLE设备或者经典蓝牙设备其中一种,不能同时扫描。

连接GATT服务

和BLE设备通信的第一步就是连上它--更具体的讲就是连接上设备的GATT服务。你可以使用connectGatt()方法来连接设备上的GATT服务。这个方法需要传入三个参数:一个Context对象,autoConnect(用来标记是否当BLE设备被搜到时就立刻连接上),还有个BluetoothGattCallback回调参数:

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

上面代码会连接上BLE设备中的GATT服务,并返回一个BluetoothGatt实例,你可以用这个实例来做GATT客户端的操作。调用者(Android app)是GATT客户端。 BluetoothGattCallback回调用来向客户端返回结果,比如连接状态以及更多的GATT客户端操作。

这个本文的例子中,BLE app提供一个Activity(DeviceControlActivity
)来连接,展示数据,以及展示蓝牙设备所支持的GATT服务与特征。基于用户的输入,这个活动会和BluetoothLeService服务通信,这个服务通过Android BLE API来和BLE设备交互:

// 通过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);

    // 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
        // 发现新的服务是回调
        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
        // 读取特征回调
        public void onCharacteristicRead(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic,
                int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }
     ...
    };
...
}

当某个特定的回调触发时,会调用broadcastUpdate()方法,并传入一个action。注意这里的数据解析是对应于本例子中的蓝牙心率测量仪:

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);

    // 这是心率测量仪profile特有的数据解析方式
    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 {
        // 对于其他profile,将数据转换为16进制
        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接收到:

// 处理各种事件
// ACTION_GATT_CONNECTED: 连接到设备
// ACTION_GATT_DISCONNECTED:断开连接
// ACTION_GATT_SERVICES_DISCOVERED: 发现GATT服务
// ACTION_DATA_AVAILABLE: 从设备接收数据,这可以是读操作或 通知的结果
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)) {
            //向用户展示所有支持的服务与特征
            displayGattServices(mBluetoothLeService.getSupportedGattServices());
        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

读取BLE属性

一旦你的应用连接上GATT服务并搜到服务,那么就可以读写所支持的属性。比如,以下代码片就是迭代设备的服务与特征并将它们展现在UI上:

public class DeviceControlActivity extends Activity {
    ...
    //演示了如何遍历服务和特征,在这个例子中将数据结构展示到树形列表上
    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>>();

        // 循环遍历服务
        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 app。以下代码片展示了如何给特征设置通知,调用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);

一旦特征设置了通知,那么当远程设备的特征发生改变时就会回调 onCharacteristicChanged() 方法:

@Override
// 特征通知
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;
}

好了以上就是官方关于蓝牙BLE的介绍,可能还是比较笼统,下一篇我会结合一个实际的例子来介绍下。

官方原文:https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#close

.

.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章