Android 蓝牙低能耗(BLE)

本文翻译自:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html

Android4.3(APILevel 18)引入了内建平台支持蓝牙低能耗的核心作用,提供给APP相应的API能够发现设备,查询服务,和提供读/写特性。与传统的蓝牙相比,蓝牙低能耗设计提供了明显地低电量消耗。它允许Android应用与对低能耗有要求的BLE设备进行通信,例如近距离传感器,心率监测设备,健康设备等等。

主要术语和概念

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

l  通用属性配置(GATT)-------- GATT配置是一个通用的规范,用来发送和接收被称作“属性”的短片数据通过BLE连接。所有当前的低能耗应用配置都是基于GATT。

Ø 蓝牙技术联盟定义了许多低能耗设备的配置。一个配置是一个规范用来确定一个设备在特定的应用中如何运行。注意一个设备可以实现多个配置。例如,一个设备可以包含一个心率监测配置和电量监测配置。

l  属性协议(ATT)-------GATT建立在属性协议(ATT)基础上。这也可以被成为GATT/ATT。ATT可以在BLE设备上最佳运行。为此,它使用尽可能少的字节。每个属性通过一个全球唯一标识符(UUID)定义,UUID是一个标准的128位字符串ID用来唯一标识信息。通过ATT传送的属性被格式化为特征和服务。

l  特征----------特征包含一个单一的值和0-n个描述符描述特征的值。一个特征可以被认为是一种类型,类似于类。

l  描述符-------描述符被定义为属性用来描述特征的值。例如,一个描述符可能指定一个人类刻度的描述,一个特征值的可接受范围或者一个测量单元用来指定一个特征的值。

l  服务----------一个服务是一组特征的集合。例如,你可以有一个服务叫做“心率监测”包含例如“心率测量”的特征。你可以在bluetooth.org上找到一系列存在的GATT基础配置和服务。

角色与职责

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

l  中央与外围。这适用于BLE连接本身。处于中心角色的设备扫描,查找广告,外围角色的设备制作广告。

l  GATT服务器与GATT客户端。这取决于一旦两个设备建立连接之后,两个设备之间如何进行通信。

 

为了理解这个区别,假设你有一个Android手机和一个是BLE设备的活动跟踪器。手机支持中心角色;活动跟踪器支持外围角色(为了建立BLE连接,你需要其中一个设备仅支持外围不能够跟对方对话,而不是两台设备仅仅支持中心角色)。

一旦手机和活动跟踪器建立了连接,他们开始传送元数据给另一方。依赖于他们之间传输的数据类型,一个或者另一个会作为服务器。例如,如果活动跟踪器想要报告传感器数据给手机,那活动跟踪器可能会作为服务器。如果活动跟踪器想要接收手机端的更新,那么手机端将会作为服务端。

在这篇文档使用的例子中,这个Android应用(运行在Android设备上)是GATT客户端。这个应用从GATT服务端获取数据,该服务端是一个支持心率配置的心率监测设备。但是你能够选择设计你的Android应用扮演GATT服务端角色。查看BluetoothGattServer(http://developer.android.com/reference/android/bluetooth/BluetoothGattServer.html) 例子获取更多地信息。

BLE权限

为了在你的应用中使用蓝牙特性,你必须声明蓝牙的权限(http://developer.android.com/reference/android/Manifest.permission.html#BLUETOOTH)。你需要这些权限来执行任意的蓝牙通信,例如请求一个连接,接受一个连接,和传输数据。

如果你想要你的应用初始化设备发现或者操作蓝牙设置,你必须也声明BLUETOOTH_ADMIN(http://developer.android.com/reference/android/Manifest.permission.html#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 disableBLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    finish();
}

建立BLE

在你的应用能够通过BLE通信之前,你需要确保在此设备上支持BLE,同时如果是这样,确保BLE是启用的。注意仅当如果<uses-feature…/>设置为false时这项检查是必要的。

如果不支持BLE,然后你应当优雅的禁用任何BLE特性。如果支持BLE,但是被禁用,然后你能够请求用户在不离开你应用的情况下启用蓝牙。使用蓝牙适配器完成建立需要两个步骤。

1.       获取蓝牙适配器(BluetoothAdapter)

对于任何和全部的蓝牙活动,蓝牙适配器是必要的。蓝牙适配器代表设备自身的蓝牙适配器(蓝牙无线电)。在整个系统中有一个蓝牙适配器,你的应用可以通过使用它与系统进行交互。下面这个代码片段展示如何获取适配器。注意这个方法使用getSystemService返回BluetoothManager的一个实例,然后该实例用于获取适配器。Android4.3(APILevel 18)引入BluetoothManager:

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

2.       启用蓝牙

接下来,你需要确保蓝牙被启用。调用isEnabled()来检查蓝牙当前是否启用。如果这个方法返回false,那么蓝牙功能被禁用。下面的代码片段检查蓝牙是否启用。如果未启用,以下代码展示一个错误,提示用户去设置页面启用蓝牙:

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

发现BLE设备

使用startLeScan()发现BLE设备。这个方法需要BluetoothAdapter.LeScanCallback作为参数。你必须实现这个回调,因为它实现扫描结果如何返回。因为扫描动作比较消耗电量,你应当遵守以下指南:

l  一旦你发现所需要的设备,停止扫描。

l  绝对不要在一个循环中扫描,同时对你的扫描设置时间限制。一种以前可用的设备可能已经移动了范围,继续扫描会消耗电量。

 

以下代码片段展示如何开始和停止扫描:

/**
 * Activity for scanning and displaying available BLE devices.
 */

public class DeviceScanActivity extends ListActivity {

    private BluetoothAdaptermBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    // Stopsscanning 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服务的UUID对象。

下面是BluetoothAdapter.LeScanCallback的一个实现,是用来提供BLE扫描结果的接口:

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

注意:你仅能够扫描蓝牙低能耗设备或者扫描经典蓝牙设备,在Bluetooth章节中有描述。你不能同时扫描蓝牙低能耗设备和经典设备。

连接到一个GATT服务器

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

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

它连接到BLE设备持有的GATT服务器,返回一个BluetoothGatt实例,你可以该实例执行GATT客户端的操作。调用者(安卓应用)是GATT客户端。BluetoothGattCallback用来传递结果给客户端,例如连接的状态,以及GATT客户端的进一步操作。

在下面的例子中,BLE应用提供一个活动(DeviceControlActivity)用来连接,展示数据,展示设备支持的GATT服务和特征。基于用户的输入,这个活动与一个叫做BluetoothLeService的服务沟通,它通过AndroidBLE的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 BluetoothManagermBluetoothManager;
    private BluetoothAdaptermBluetoothAdapter;
    private StringmBluetoothDeviceAddress;
    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 UUIDUUID_HEART_RATE_MEASUREMENT =
            UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);

    // Variouscallback methods defined by the BLE API.
    private final BluetoothGattCallbackmGattCallback =
            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 servicediscovery:" +
                       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);
            }
        }
     ...
    };
...
}

当一个特别的回调被触发,它会调用适当的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);

    // This isspecial handling for the Heart Rate Measurement profile. Data
    // parsing iscarried 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(bytebyteChar : 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: connectedto a GATT server.
// ACTION_GATT_DISCONNECTED:disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED:discovered GATT services.
// ACTION_DATA_AVAILABLE: receiveddata from the device. This can be a
// result of read or notificationoperations.
private final BroadcastReceivermGattUpdateReceiver = 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应用已经连接到一个GATT服务器并且发现服务,它就可以读写它支持的属性。例如,这段代码循环访问服务器的服务和特征,在UI中显示:

public class DeviceControlActivity extends Activity {
    ...
    //Demonstrates how to iterate through the supported GATT
    // Services/Characteristics.
    // In thissample, 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 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);

一旦一个特征的通知被启用,如果在远程设备上的特征改变时,一个onCharacteristicChaned()回调将会被触发:

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

关闭客户端应用

一旦你的应用已经完成使用一个BLE设备,它应当调用close(),使得系统能够正常地释放资源:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值