Android 4.3(API級(jí)別18)引入了內(nèi)置平臺(tái)支持藍(lán)牙低功耗(BLE)的核心角色岖免,并提供應(yīng)用程序可用于發(fā)現(xiàn)設(shè)備找颓,查詢服務(wù)和傳輸信息的API合愈。
常見用例包括以下內(nèi)容:
- 在附近設(shè)備之間傳輸少量數(shù)據(jù)。
- 與Google Beacons等接近傳感器進(jìn)行交互击狮,根據(jù)用戶的當(dāng)前位置為用戶提供定制體驗(yàn)佛析。
與經(jīng)典藍(lán)牙相比,藍(lán)牙低功耗(BLE)旨在提供顯著降低的功耗彪蓬。 這允許Android應(yīng)用程序與具有更嚴(yán)格電源要求的BLE設(shè)備通信寸莫,例如接近傳感器,心率監(jiān)視器和健身設(shè)備寞焙。
關(guān)鍵術(shù)語和概念
以下是關(guān)鍵BLE術(shù)語和概念的摘要:
- 通用屬性配置文件(GATT) - GATT配置文件是用于在BLE鏈路上發(fā)送和接收稱為“屬性”的短數(shù)據(jù)的通用規(guī)范储狭。 目前所有低能耗應(yīng)用配置文件均基于GATT互婿。
- Bluetooth SIG為低能耗設(shè)備定義了許多配置文件。 配置文件是設(shè)備在特定應(yīng)用程序中的工作方式的規(guī)范辽狈。 請(qǐng)注意慈参,設(shè)備可以實(shí)現(xiàn)多個(gè)配置文件。 例如刮萌,設(shè)備可以包含心率監(jiān)測(cè)器和電池水平檢測(cè)器驮配。
- 屬性協(xié)議(ATT)-GATT建立在屬性協(xié)議(ATT)之上。 這也稱為GATT / ATT着茸。 ATT經(jīng)過優(yōu)化壮锻,可在BLE設(shè)備上運(yùn)行。 為此涮阔,它使用盡可能少的字節(jié)猜绣。 每個(gè)屬性由通用唯一標(biāo)識(shí)符(UUID)唯一標(biāo)識(shí),UUID是用于唯一標(biāo)識(shí)信息的字符串ID的標(biāo)準(zhǔn)化128位格式敬特。 ATT傳輸?shù)膶傩员桓袷交癁樘卣骱头?wù)掰邢。
- 特征 - 特征包含描述特征值的單個(gè)值和0-n描述符伟阔。 特征可以被認(rèn)為是類型辣之,類似于類。
- 描述符 - 描述符是定義描述特征值的屬性皱炉。 例如怀估,描述符可以指定人類可讀的描述,特征值的可接受范圍合搅,或特征值特定的度量單位多搀。
- 服務(wù) - 服務(wù)是一系列特征。 例如历筝,您可以使用名為“心率監(jiān)測(cè)器”的服務(wù)酗昼,其中包括“心率測(cè)量”等特征。 您可以在bluetooth.org上找到基于GATT的現(xiàn)有配置文件和服務(wù)的列表梳猪。
角色和責(zé)任
以下是Android設(shè)備與BLE設(shè)備交互時(shí)應(yīng)用的角色和職責(zé):
- 中央與外圍麻削。 這適用于BLE連接本身。 中心角色的設(shè)備掃描春弥,尋找廣告呛哟,外圍角色的設(shè)備制作廣告。
- GATT服務(wù)器與GATT客戶端匿沛。 這確定了兩個(gè)設(shè)備建立連接后如何相互通信扫责。
要了解這種區(qū)別,請(qǐng)假設(shè)您擁有一部Android手機(jī)和一臺(tái)BLE設(shè)備的活動(dòng)跟蹤器逃呼。手機(jī)支持中心角色;活動(dòng)跟蹤器支持外圍角色(為了建立一個(gè)BLE連接鳖孤,你需要一個(gè) - 兩個(gè)只支持外圍設(shè)備無法相互通信的東西者娱,也不能只支持兩個(gè)中心的東西)。
一旦電話和活動(dòng)跟蹤器建立了連接苏揣,他們就開始將GATT元數(shù)據(jù)相互轉(zhuǎn)移黄鳍。根據(jù)它們傳輸?shù)臄?shù)據(jù)類型,一個(gè)或另一個(gè)可能充當(dāng)服務(wù)器平匈。例如框沟,如果活動(dòng)跟蹤器想要將傳感器數(shù)據(jù)報(bào)告給電話,則活動(dòng)跟蹤器充當(dāng)服務(wù)器可能是有意義的增炭。如果活動(dòng)跟蹤器想要從手機(jī)接收更新忍燥,那么手機(jī)充當(dāng)服務(wù)器可能是有意義的。
在本文檔中使用的示例中隙姿,Android應(yīng)用程序(在Android設(shè)備上運(yùn)行)是GATT客戶端梅垄。該應(yīng)用程序從GATT服務(wù)器獲取數(shù)據(jù),GATT服務(wù)器是支持心率配置文件的BLE心率監(jiān)測(cè)器孟辑。但您也可以將Android應(yīng)用設(shè)計(jì)為扮演GATT服務(wù)器角色哎甲。有關(guān)更多信息,請(qǐng)參閱BluetoothGattServer饲嗽。
BLE權(quán)限
要在您的應(yīng)用程序中使用藍(lán)牙功能,您必須聲明藍(lán)牙權(quán)限BLUETOOTH奈嘿。 您需要此權(quán)限才能執(zhí)行任何藍(lán)牙通信貌虾,例如請(qǐng)求連接,接受連接和傳輸數(shù)據(jù)裙犹。
如果您希望應(yīng)用程序啟動(dòng)設(shè)備發(fā)現(xiàn)或操作藍(lán)牙設(shè)置尽狠,則還必須聲明BLUETOOTH_ADMIN權(quán)限。 注意:如果使用BLUETOOTH_ADMIN權(quán)限叶圃,則還必須具有BLUETOOTH權(quán)限袄膏。
在應(yīng)用程序清單文件中聲明藍(lán)牙權(quán)限。 例如:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
如果您要聲明您的應(yīng)用僅適用于支持BLE的設(shè)備掺冠,請(qǐng)?jiān)趹?yīng)用清單中包含以下內(nèi)容:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
但是沉馆,如果您希望將應(yīng)用程序提供給不支持BLE的設(shè)備,您仍應(yīng)將此元素包含在應(yīng)用程序的清單中德崭,但必須設(shè)置required =“false”斥黑。 然后在運(yùn)行時(shí),您可以使用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();
}
注意:LE Beacons通常與位置相關(guān)聯(lián)眉厨。 要使用BluetoothLeScanner骤公,您必須通過在應(yīng)用程序的清單文件中聲明ACCESS_COARSE_LOCATION或ACCESS_FINE_LOCATION權(quán)限來請(qǐng)求用戶的權(quán)限焕梅。 沒有這些權(quán)限,掃描將不會(huì)返回任何結(jié)果漫蛔。
設(shè)置BLE
在您的應(yīng)用程序可以通過BLE進(jìn)行通信之前,您需要驗(yàn)證設(shè)備是否支持BLE亦渗,如果是,請(qǐng)確保它已啟用。 請(qǐng)注意颠焦,僅當(dāng)<uses-feature ... />設(shè)置為false時(shí)才需要進(jìn)行此檢查。
如果不支持BLE琐簇,則應(yīng)優(yōu)雅地禁用任何BLE功能蒸健。 如果BLE受支持但已禁用,則您可以請(qǐng)求用戶啟用藍(lán)牙而無需離開您的應(yīng)用程序婉商。 使用BluetoothAdapter似忧,可以分兩步完成此設(shè)置。
- 獲取BluetoothAdapter
任何和所有藍(lán)牙活動(dòng)都需要BluetoothAdapter丈秩。 BluetoothAdapter代表設(shè)備自己的藍(lán)牙適配器(藍(lán)牙無線電)盯捌。 整個(gè)系統(tǒng)都有一個(gè)藍(lán)牙適配器,您的應(yīng)用程序可以使用此對(duì)象與其進(jìn)行交互蘑秽。 下面的代碼段顯示了如何獲取適配器饺著。 請(qǐng)注意,此方法使用getSystemService()返回BluetoothManager的實(shí)例肠牲,然后使用該實(shí)例獲取適配器幼衰。 Android 4.3(API Level 18)介紹了BluetoothManager:
private BluetoothAdapter bluetoothAdapter;
...
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
- 啟用藍(lán)牙
接下來,您需要確保啟用藍(lán)牙缀雳。 調(diào)用isEnabled()檢查當(dāng)前是否啟用了藍(lán)牙渡嚣。 如果此方法返回false,則禁用藍(lán)牙。 以下代碼段會(huì)檢查是否已啟用藍(lán)牙竞膳。 如果不是刊侯,則代碼段會(huì)顯示錯(cuò)誤提示用戶轉(zhuǎn)到“設(shè)置”以啟用藍(lán)牙:
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
注意:傳遞給startActivityForResult(android.content.Intent,int)的REQUEST_ENABLE_BT常量是一個(gè)本地定義的整數(shù)(必須大于0)辜羊,系統(tǒng)會(huì)在你的onActivityResult(int,int,android.content)中傳回給你。 Intent)實(shí)現(xiàn)為requestCode參數(shù)。
找到BLE設(shè)備
要查找BLE設(shè)備混移,請(qǐng)使用startLeScan()方法回铛。 此方法將BluetoothAdapter.LeScanCallback作為參數(shù)。 您必須實(shí)現(xiàn)此回調(diào)巾乳,因?yàn)檫@是返回掃描結(jié)果的方式氨鹏。 由于掃描是電池密集型的镣丑,因此您應(yīng)遵守以下準(zhǔn)則:
- 找到所需設(shè)備后慨蛙,請(qǐng)立即停止掃描通砍。
- 切勿掃描循環(huán)玛臂,并設(shè)置掃描時(shí)間限制。 之前可用的設(shè)備可能已超出范圍封孙,并繼續(xù)掃描耗盡電池迹冤。
以下代碼段顯示了如何啟動(dòng)和停止掃描:
/**
* Activity for scanning and displaying available BLE devices.
*/
public class DeviceScanActivity extends ListActivity {
private BluetoothAdapter bluetoothAdapter;
private boolean mScanning;
private Handler handler;
// 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.
handler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
bluetoothAdapter.stopLeScan(leScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
bluetoothAdapter.startLeScan(leScanCallback);
} else {
mScanning = false;
bluetoothAdapter.stopLeScan(leScanCallback);
}
...
}
...
}
如果您只想掃描特定類型的外圍設(shè)備,可以調(diào)用startLeScan(UUID []虎忌,BluetoothAdapter.LeScanCallback)泡徙,提供一組UUID對(duì)象,指定您的應(yīng)用支持的GATT服務(wù)膜蠢。
以下是BluetoothAdapter.LeScanCallback的實(shí)現(xiàn)堪藐,它是用于提供BLE掃描結(jié)果的接口:
private LeDeviceListAdapter leDeviceListAdapter;
...
// Device scan callback.
private BluetoothAdapter.LeScanCallback leScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
leDeviceListAdapter.addDevice(device);
leDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
注意:您只能掃描藍(lán)牙LE設(shè)備或掃描經(jīng)典藍(lán)牙設(shè)備,如藍(lán)牙中所述挑围。 您無法同時(shí)掃描藍(lán)牙LE和傳統(tǒng)設(shè)備礁竞。
連接到GATT服務(wù)器
與BLE設(shè)備交互的第一步是連接到它 - 更具體地說,連接到設(shè)備上的GATT服務(wù)器杉辙。 要連接到BLE設(shè)備上的GATT服務(wù)器模捂,請(qǐng)使用connectGatt()方法。 此方法有三個(gè)參數(shù):一個(gè)Context對(duì)象,autoConnect(指示是否在可用時(shí)自動(dòng)連接到BLE設(shè)備的布爾值)枫绅,以及對(duì)BluetoothGattCallback的引用:
bluetoothGatt = device.connectGatt(this, false, gattCallback);
這將連接到BLE設(shè)備托管的GATT服務(wù)器泉孩,并返回一個(gè)BluetoothGatt實(shí)例,然后您可以使用該實(shí)例執(zhí)行GATT客戶端操作并淋。 呼叫者(Android應(yīng)用)是GATT客戶端寓搬。 BluetoothGattCallback用于向客戶端提供結(jié)果,例如連接狀態(tài)县耽,以及任何進(jìn)一步的GATT客戶端操作句喷。
在此示例中,BLE應(yīng)用程序提供活動(dòng)(DeviceControlActivity)以連接兔毙,顯示數(shù)據(jù)和顯示設(shè)備支持的GATT服務(wù)和特征唾琼。 根據(jù)用戶輸入,此活動(dòng)與名為BluetoothLeService的服務(wù)進(jìn)行通信澎剥,該服務(wù)通過Android BLE API與BLE設(shè)備進(jìn)行交互:
// 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 bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private String bluetoothDeviceAddress;
private BluetoothGatt bluetoothGatt;
private int connectionState = 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 gattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
connectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
Log.i(TAG, "Attempting to start service discovery:" +
bluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
connectionState = 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);
}
}
...
};
...
}
當(dāng)觸發(fā)特定回調(diào)時(shí)锡溯,它會(huì)調(diào)用相應(yīng)的broadcastUpdate()輔助方法并向其傳遞操作。 請(qǐng)注意哑姚,本節(jié)中的數(shù)據(jù)解析是根據(jù)藍(lán)牙心率測(cè)量配置文件規(guī)范執(zhí)行的:
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 gattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
connected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
connected = 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(bluetoothLeService.getSupportedGattServices());
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
讀BLE屬性
一旦您的Android應(yīng)用程序連接到GATT服務(wù)器并發(fā)現(xiàn)了服務(wù),它就可以在支持的位置讀取和寫入屬性叙量。 例如倡蝙,此代碼段迭代服務(wù)器的服務(wù)和特征,并在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應(yīng)用程序通常會(huì)要求在設(shè)備上的特定特征發(fā)生變化時(shí)收到通知绞佩。 此代碼段顯示如何使用setCharacteristicNotification()方法設(shè)置特征的通知:
private BluetoothGatt bluetoothGatt;
BluetoothGattCharacteristic characteristic;
boolean enabled;
...
bluetoothGatt.setCharacteristicNotification(characteristic, enabled);
...
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
bluetoothGatt.writeDescriptor(descriptor);
為特性啟用通知后寺鸥,如果遠(yuǎn)程設(shè)備上的特性發(fā)生更改,則會(huì)觸發(fā)onCharacteristicChanged()回調(diào):
@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
關(guān)閉客戶端應(yīng)用程序
一旦您的應(yīng)用程序使用完BLE設(shè)備品山,它應(yīng)該調(diào)用close()胆建,以便系統(tǒng)可以適當(dāng)?shù)蒯尫刨Y源:
public void close() {
if (bluetoothGatt == null) {
return;
}
bluetoothGatt.close();
bluetoothGatt = null;
}