Android API Guides---Bluetooth Low Energy

来源:互联网 发布:tor网络 百科 编辑:程序博客网 时间:2024/04/30 19:43

Bluetooth Low Energy

搭载Android 4.3(API等级18)引入了低功耗蓝牙内置的平台支持的核心作用,并提供应用程序可以用它来发现设备,查询服务,和读/写特性的API。在对比传统蓝牙,蓝牙低功耗(BLE)被设计成提供显著较低的功耗。这使得Android应用能够与具有低功耗的要求,如接近传感器,心脏速率监视器,健身器材等BLE设备进行通信。


关键术语和概念


这里的关键是BLE术语和概念的摘要:


通用属性配置文件(GATT)GATT -The配置文件用于发送和接收被称为“属性”过BLE链接数据的小品一般规范。目前所有的低功耗应用的配置文件是基于GATT。
蓝牙技术联盟定义了用于低功耗设备数量的配置文件。配置文件是一个设备在特定的应用程序是如何工作的规范。需要注意的是,设备可以实现多个轮廓。例如,一个设备可以包含一个心脏监测仪和一电池电平检测器。
属性协议(ATT)-GATT建立在属性协议(ATT)的顶部。这也被称为总协定/ ATT。 ATT进行了优化,在BLE设备上运行。为此,它使用如几个字节越好。每个属性唯一地由一通用唯一标识符(UUID),​​这是用于唯一地标识信息的字符串ID的标准化128位格式识别。通过ATT输送的属性被格式化为特色和服务。
特性,一个特性包含描述特性的值的单值0-N描述符。的特征可以被认为是一种类型的,类似于一个类。
描述符描述符中定义的描述的特征值的属性。例如,描述符可以指定一个人类可读的描述中,对一个特征的值在可接受的范围,或测量单位特定于一个特性的值。
服务的服务是特性的集合。例如,你可以有一个名为“心率监视器”,包括特性,如服务“心脏速率测量。”你可以找到现有的基于GATT的配置文件和服务bluetooth.org的列表。
角色和职责


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


中央与外设。这适用于BLE连接本身。在中央的作用扫描的装置,寻找广告,并在外围角色的设备使所述广告。
GATT服务器与客户端GATT。这就决定了两种设备如何互相沟通后,他们已经建立的连接。
要理解的区别,假设你有一个Android手机和一个活动追踪这是一个BLE装置。该手机支持的核心作用;活动跟踪器支持外设角色(建立BLE连接,你需要每两件事仅支持外围设备无法相互交谈的,也不能两件事情,只支持中心)。


一旦手机和活动跟踪器建立连接后,便开始GATT元数据转移到另一个。根据其种类,他们转移,一个或其他可能作为服务器的数据。例如,如果活动跟踪要传感器数据报告给手机,它可能是有意义的活动跟踪器作为服务器的行为。如果活动追踪想要接收来自电话的更新,则它可能是有意义的电话到作为服务器动作。


在本文档中使用的示例中,Android应用程序(在Android设备上运行)是GATT客户端。该应用程序从服务器关贸总协定,这是一个BLE心脏监测仪支持心率配置文件中获取数据。但是你可以或者设计​​你的Andr​​oid应用发挥GATT服务器角色。见BluetoothGattServer以获取更多信息。


BLE权限


为了使用应用程序中的蓝牙功能,您必须声明蓝牙权限蓝牙。你需要这个权限才能执行任何蓝牙通信,比如请求连接,接受连接,传输数据。


如果你希望你的应用程序来启动设备发现或操纵蓝牙设置,您还必须声明BLUETOOTH_ADMIN许可。注:如果您使用BLUETOOTH_ADMIN权限,那么你还必须有蓝牙权限。


声明在您的应用程序清单文件的蓝牙权限(S)。例如:

<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的设备,你还是应该在您的应用程序的清单这一元素,但需要=“false”的设置。然后,在运行时可以使用PackageManager.hasSystemFeature()确定电缆可用性:

// 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();}
设置BLE
在应用程序能够在BLE通信,您需要验证BLE支持在设备上,如果是这样,请确保它已启用。请注意,如果<用途特征... />设置为false此项检查才是必需的。
如果不支持BLE,那么你应该优雅地禁用任何BLE功能。如果支持BLE,但被禁用,则可以要求用户启用蓝牙无需离开应用程序。这种设置两个步骤来完成,使用BluetoothAdapter。
获取BluetoothAdapter
该BluetoothAdapter需要的任何和所有蓝牙活动。该BluetoothAdapter代表设备自身的蓝牙适配器(蓝牙无线电)。还有一个蓝牙适配器为整个系统和应用程序可以使用这个对象与它进行交互。下面的代码片段展示了如何获取适配器。请注意,此方法使用getSystemService()返回蓝牙管理,然后将其用于获取适配器的一个实例。搭载Android 4.3(API等级18)引入了蓝牙管理器:

// Initializes Bluetooth adapter.final BluetoothManager bluetoothManager =        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);mBluetoothAdapter = bluetoothManager.getAdapter();
启用蓝牙
接下来,您需要确保蓝牙已启用。调用isEnabled()检查当前是否启用蓝牙。如果此方法返回false,那么蓝牙被禁用。下面的代码片段检查是否已启用蓝牙。如果不是,该片段显示一个错误提示用户去设置启用蓝牙:

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设备


为了找到BLE装置,使用startLeScan()方法。此方法需要一个BluetoothAdapter.LeScanCallback作为参数。您必须实现回调,因为那是扫描结果如何返回。因为扫描电池密集,应该遵守以下原则:


只要你找到所需的设备,停止扫描。
从未上扫描一个循环,并设置在您的扫描时间限制。那是以前提供的设备可能已经移出范围,并继续扫描消耗电池电量。
下面的片段展示了如何启动和停止扫描:

/** * 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),提供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();           }       });   }};
注意:您只能扫描蓝牙LE设备或扫描传统蓝牙设备,如蓝牙描述。不能扫描蓝牙LE和同时经典设备两者。


连接到服务器关贸总协定


在具有BLE设备交互的第一步是连接到更具体地说IT-,连接到设备上的总协定服务器。要连接到关贸总协定服务器BLE设备上,可以使用connectGatt()方法。这个方法有三个参数:一个上下文对象,自动连接(布尔值,指示是否立即自动变得可用连接BLE设备),以及一个BluetoothGattCallback参考:

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
这将连接到由BLE装置主办的GATT服务器,并返回一个BluetoothGatt例如,你可以再使用进行GATT客户端操作。主叫方(Android应用程序)是GATT客户端。该BluetoothGattCallback用于传递结果给客户端,诸如连接状态,以及任何进一步关贸总协定客户机操作。
在这个例子中,BLE应用程序提供的活性(设备控制活动)连接,显示数据,和显示由该设备支持的总协定的服务和特征。根据用户的输入,该活动与被叫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 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);            }        }     ...    };...}
当一个特定的回调被触发时,它调用适当的广播更新()辅助方法,传递给它一个动作。注意,在本节解析数据根据蓝牙心率测量信息的规格进行:

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);}
早在设备控制活动,这些活动是由一个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 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应用已经连接到服务器的关贸总协定,发现服务,它可以读取和写入的属性,如果支持。例如,通过服务器的服务和特色这段代码迭代,并显示在用户界面:

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 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// Characteristic notificationpublic void onCharacteristicChanged(BluetoothGatt gatt,        BluetoothGattCharacteristic characteristic) {    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);}
关闭客户端应用程序


一旦程序使用BLE装置完成,应该调用close()这样系统就可以适当地释放资源:

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

0 0