Android 4.3(API级别18)为中心角色的蓝牙低能耗(BLE)引入内置平台支持,并提供应用程序可用于发现设备,查询服务和传输信息的API。
常见用例包括:
1、在附近设备之间传输少量数据。
2、与Google Beacon之类的接近传感器进行交互,以便为用户提供基于当前位置的自定义体验。
与经典蓝牙相比,蓝牙低功耗(BLE)旨在显着降低功耗。 这允许Android应用程序与具有更严格功率需求的BLE设备进行通信,例如接近传感器,心率监测器和健身设备。
一、关键术语和概念
以下是关键BLE术语和概念的摘要:
1、通用属性配置文件(GATT)- GATT简档是通过BLE链接发送和接收称为“属性”的短数据的通用规范。 所有当前的低能耗应用配置文件均基于GATT。
1)、Bluetooth SIG定义了低能量设备的许多配置文件。 配置文件是设备在特定应用程序中如何工作的规范。 请注意,设备可以实现多个配置文件。 例如,设备可以包含心率监测器和电池电平检测器。
2、属性协议(ATT)-GATT建立在属性协议(ATT)之上。 这也被称为GATT / ATT。 ATT经过优化,可在BLE设备上运行。 为此,它使用尽可能少的字节。 每个属性由通用唯一标识符(UUID)唯一标识,通用唯一标识符(UUID)是用于唯一标识信息的字符串ID的标准化128位格式。 ATT传输的属性被格式化为特征和服务。
3、特征 - 特征包含描述特征值的单个值和0-n描述符。 一个特征可以被认为是一个类型,类似于一个类。
4、描述符 - 描述符是描述特征值的定义属性。 例如,描述符可以指定人类可读描述,特征值的可接受范围,或特定于特征值的度量单位。
5、Service-A服务是一组特征。 例如,您可以使用名为“心率监测器”的服务,其中包括“心率测量”等特征。 您可以在bluetooth.org上找到现有的基于GATT的配置文件和服务的列表。
一)、角色和责任
以下是Android设备与BLE设备进行交互时的角色和职责:
1、中央与外围。 这适用于BLE连接本身。 中央角色的设备扫描,查找广告,外设中的设备使广告成为广告。
2、GATT服务器与GATT客户端。 这确定了两个设备在建立连接后如何对话。
要了解这个区别,假设您有一个Android手机和一个活动跟踪器,它是一个BLE设备。 手机支持中心角色; 活动跟踪器支持外设角色(建立一个BLE连接,您需要每两件事情之一,只支持外围设备不能互相交谈,也不可能只有两个只支持中心的东西)。
一旦电话和活动跟踪器建立了连接,他们就开始将GATT元数据相互转移。 根据传输的数据类型,一个或另一个可能充当服务器。 例如,如果活动跟踪器想要将传感器数据报告给手机,那么活动跟踪器可能会充当服务器。 如果活动跟踪器想要从手机接收更新,则手机充当服务器可能是有意义的。
在本文档中使用的示例中,Android应用(在Android设备上运行)是GATT客户端。 该应用程序从GATT服务器获取数据,该服务器是支持心率配置文件的BLE心率监视器。 但是您也可以设计您的Android应用来播放GATT服务器角色。 有关详细信息,请参阅BluetoothGattServer。
二、BLE权限
为了在您的应用程序中使用蓝牙功能,您必须声明蓝牙权限BLUETOOTH。 您需要此权限才能执行任何蓝牙通信,例如请求连接,接受连接和传输数据。
如果您希望您的应用程序启动设备发现或操纵蓝牙设置,您还必须声明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的设备,那么您应该仍然将该元素包含在应用程序的清单中,但设置为“=”。 然后在运行时,您可以使用PackageManager.hasSystemFeature()来确定BLE可用性:
// 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();
}
一)、请求用户权限
为了从NETWORK_PROVIDER或GPS_PROVIDER接收位置更新,您必须分别在Android清单文件中声明{@code ACCESS_COARSE_LOCATION}或{@code ACCESS_FINE_LOCATION}权限来请求用户的权限。 没有这些权限,您的应用程序对位置更新的请求将失败,并显示权限错误。
如果您同时使用NETWORK_PROVIDER和GPS_PROVIDER,则您只需要请求{@code ACCESS_FINE_LOCATION}权限,因为它包含两个提供者的权限。 {@code ACCESS_COARSE_LOCATION}的权限仅允许访问NETWORK_PROVIDER。
注意:如果您的应用程序针对Android 5.0(API级别21)或更高版本,则必须声明您的应用程序在清单文件中使用android.hardware.location.network或android.hardware.location.gps硬件功能,具体取决于您的应用程序是否从NETWORK_PROVIDER或GPS_PROVIDER接收位置更新。 如果您的应用程序从这些位置提供商来源收到位置信息,则需要声明该应用程序在应用程序清单中使用这些硬件功能。 在Android 5.0(API 21)之前运行版本的设备上,请求{@code ACCESS_FINE_LOCATION}或{@code ACCESS_COARSE_LOCATION}权限包含对位置硬件功能的隐含请求。 但是,请求这些权限不会自动请求Android 5.0(API级别21)及更高版本的位置硬件功能。
以下代码示例演示如何在从设备的GPS读取数据的应用程序的清单文件中声明权限和硬件功能:
<manifest ... >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
...
</manifest>
三、设置BLE
在您的应用程序可以通过BLE进行通信之前,您需要验证设备上是否支持BLE,如果是,则确保已启用BLE。 请注意,只有将<uses-feature ... />设置为false时,才需要进行此检查。
如果不支持BLE,则应优雅地禁用任何BLE功能。 如果支持BLE但禁用,那么您可以请求用户在不离开应用程序的情况下启用蓝牙。 该设置使用BluetoothAdapter在两个步骤中完成。
1、获取BluetoothAdapter
BluetoothAdapter是任何和所有蓝牙活动所必需的。 BluetoothAdapter表示设备自己的蓝牙适配器(蓝牙无线电)。 整个系统有一个蓝牙适配器,您的应用程序可以使用此对象与其进行交互。 下面的代码片段显示了如何获取适配器。 请注意,此方法使用getSystemService()返回一个BluetoothManager实例,然后用于获取适配器。 Android 4.3(API Level 18)介绍了BluetoothManager:
private BluetoothAdapter mBluetoothAdapter;
...
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
2、启用蓝牙
接下来,您需要确保启用蓝牙。 调用isEnabled()来检查蓝牙是否被启用。 如果此方法返回false,则蓝牙被禁用。 以下片段检查是否启用蓝牙。 如果不是,该片段会显示错误提示用户进入设置以启用蓝牙:
// 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);
}
注意:传递给startActivityForResult(android.content.Intent,int)的REQUEST_ENABLE_BT常量是系统在您的onActivityResult(int,int,android.content)中传回给您的本地定义的整数(必须大于0)。实现作为requestCode参数。
四、查找BLE设备
要查找BLE设备,您可以使用startLeScan()方法。 此方法将BluetoothAdapter.LeScanCallback作为参数。 您必须实现此回调,因为这是如何返回扫描结果。 因为扫描是电池密集型的,您应该遵守以下准则:
1、一旦找到所需的设备,请停止扫描。
2、切勿扫描循环,并设置扫描时间限制。 以前可用的设备可能已经移出范围,并继续扫描排出电池。
以下片段显示如何启动和停止扫描:
/**
* 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服务的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和经典设备。
五、连接到GATT服务器
与BLE设备交互的第一步是连接到它 - 更具体地说,连接到设备上的GATT服务器。 要连接到BLE设备上的GATT服务器,可以使用connectGatt()方法。 该方法有三个参数:一个上下文对象,autoConnect(布尔值,表示一旦可用,就自动连接到BLE设备),以及对BluetoothGattCallback的引用:
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
这连接到由BLE设备托管的GATT服务器,并返回一个BluetoothGatt实例,然后您可以使用它来进行GATT客户端操作。 来电者(Android应用程式)是GATT客户。 BluetoothGattCallback用于向客户端提供结果,例如连接状态,以及任何进一步的GATT客户端操作。
在此示例中,BLE应用程序提供了一个活动(DeviceControlActivity)来连接,显示数据,并显示GATT服务和设备支持的特性。 基于用户输入,此活动与称为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);
}
}
...
};
...
}
当特定的回调被触发时,它调用相应的broadcastUpdate()辅助方法并传递一个动作。 请注意,本节中的数据解析是根据蓝牙心率测量配置文件规范执行的:
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,这些事件由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应用程序连接到GATT服务器并发现服务,它可以在支持的情况下读取和写入属性。 例如,此代码段遍历服务器的服务和特征,并在UI中显示它们:
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 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;
}