BLE 即 Bluetooth Low Energy,藍(lán)牙低功耗技術(shù)驼仪,是藍(lán)牙4.0引入的新技術(shù)∷胰澹現(xiàn)在越來越多的智能設(shè)備使用了BLE,像滿大街的智能手環(huán)涮俄。
Android在4.3(API 18)中引進(jìn)了對BLE central role的支持蛉拙,同時提供API供App來掃描設(shè)備关斜、查詢服務(wù)屿附、讀寫特征值等舌镶。
關(guān)鍵術(shù)語和概念
- Generic Attribute Profile (GATT)—GATT概述(profile)是一個通用的通過BLE連接來發(fā)送和接受短的被稱為“屬性”的數(shù)據(jù)的規(guī)范跋涣。所有現(xiàn)在的低功耗應(yīng)用概述(profile)都基于GATT。
- 藍(lán)牙標(biāo)準(zhǔn)協(xié)會為低功耗設(shè)備定義了很多 profiles敛瓷。概述(profile)是設(shè)備在特定應(yīng)用場景下如何工作的規(guī)范。注意設(shè)備能實(shí)現(xiàn)不止一種概述,例如野来,一個設(shè)備可以包含心律監(jiān)測和電池電量檢測。
Attribute Protocol (ATT)—GATT建立在屬性協(xié)議(ATT)上踪旷。通常他們一起被叫做GATT/ATT曼氛。ATT針對在BLE設(shè)備上運(yùn)行做了優(yōu)化。為了這個目的令野,它使用盡可能少的字節(jié)舀患。每個屬性通過一個標(biāo)準(zhǔn)的128位格式的字符串ID作為唯一標(biāo)識信息的通用唯一識別碼(Universally Unique Identifier 即UUID)來唯一的標(biāo)識。屬性被ATT格式化為特征和服務(wù)來傳輸气破。
Characteristic—一個特征包含一個單一的值(value)和0-n個描述信息塊(descriptor)來描述特征的值聊浅。特征可以被認(rèn)為是一種類型(type),類似一個類(class)现使。
Descriptor—描述信息塊定義了特征值(characteristic value)的屬性低匙,一個描述信息塊可能指定一個可讀的描述,一個特征值可接受的范圍碳锈,或者指定一個特征值的計(jì)量單位顽冶。
Service—服務(wù)是特征的集合。例如售碳,你可以有個叫做“心率檢測器”且包含“心律測量方式”特征的服務(wù)强重。你可以在bluetooth.org上找到一份現(xiàn)有的基于GATT的概述(profile)和服務(wù)列表绞呈。
角色和職責(zé)
中心 vs. 外圍。你必須同時有這兩種設(shè)備才能建立他們之間的連接间景。兩個中心設(shè)備或者兩個外圍設(shè)備都不能建立連接佃声。
GATT服務(wù)端 vs. GATT客戶端。這取決于他們之間是怎么交流的拱燃。
BLE權(quán)限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<!--下面的用來掃描設(shè)備和修改設(shè)置秉溉,用了這個必須同時用上面那個-->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
檢查設(shè)備是否支持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();
}
設(shè)置BLE
整個設(shè)備只有一個BluetoothAdapter
- 獲取BluetoothAdapter
整個設(shè)備只有一個BluetoothAdapter,它代表了設(shè)備自己的藍(lán)牙適配器碗誉,應(yīng)用通過這個對象與設(shè)備進(jìn)行交互召嘶。
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
- 開啟藍(lán)牙
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設(shè)備
要查找BLE設(shè)備,需要使用startLeScan()方法哮缺,它的參數(shù)是BluetoothAdapter.LeScanCallback弄跌。你必須實(shí)現(xiàn)這個callbak,因?yàn)檫@是掃描結(jié)果返回的方式尝苇。藍(lán)牙掃描是一個電量敏感的操作铛只,你需要遵守以下指導(dǎo):
- 只要找到了要找的設(shè)備,停止掃描
- 不要在循環(huán)里掃描糠溜,設(shè)置一個掃描時間淳玩。之前的設(shè)備可能已經(jīng)移動到范圍外,持續(xù)掃描會耗盡電量非竿。
如何開始和停止掃描:
/**
* 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);
}
...
}
...
}
如果只想掃描指定類型的外圍設(shè)備蜕着,你可以調(diào)用startLeScan(UUID[], BluetoothAdapter.LeScanCallback),提供一個指定了你app支持的GATT服務(wù)的UUID數(shù)組對象红柱。
下面是一個用來傳送BLE掃描結(jié)果的接口BluetoothAdapter.LeScanCallback的實(shí)現(xiàn):
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();
}
});
}
};
注意:你只能掃描BLE設(shè)備或傳統(tǒng)藍(lán)牙設(shè)備二者之一承匣,就像 Bluetooth描述的那樣。你不能同時掃描兩種設(shè)備锤悄。
連接GATT服務(wù)端
與BLE設(shè)備交互第一步就是要連接它—更確切的說韧骗,是連接到設(shè)備上的GATT服務(wù)端。要連接到BLE設(shè)備的GATT服務(wù)端零聚,使用[connectGatt()](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback))方法袍暴。這個方法需要三個參數(shù),一個Context對象隶症,autoConnect(一個指示是否自動連接到BLE設(shè)備--當(dāng)它一旦可用的時候--的布爾值)容诬,和一個 BluetoothGattCallback的引用:
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
返回的BluetoothGatt實(shí)例之后你可以用它來管理GATT客戶端的操作。調(diào)用者(Android app)是GATT客戶端沿腰。 BluetoothGattCallback
用于傳遞結(jié)果給用戶览徒,例如連接狀態(tài),以及任何進(jìn)一步GATT客戶端操作颂龙。
在這個例子中习蓬,這個BLE APP提供了一個activity(DeviceControlActivity)來連接纽什,顯示數(shù)據(jù),顯示該設(shè)備支持的GATT services和characteristics躲叼。根據(jù)用戶的輸入芦缰,這個activity與一個叫做BluetoothLeService的 Service通信,它通過Android BLE API實(shí)現(xiàn)與BLE設(shè)備交互:
// 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);
}
}
...
};
...
}
當(dāng)一個特定的回調(diào)被觸發(fā)的時候枫慷,它會調(diào)用相應(yīng)的broadcastUpdate()
輔助方法并且傳遞給它一個action让蕾。注意在該部分中的數(shù)據(jù)解析按照藍(lán)牙心率測量配置文件規(guī)格profile specifications進(jìn)行。
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 app已經(jīng)連接到GATT服務(wù)端連接且發(fā)現(xiàn)services后或听,就可以讀探孝、寫那些支持的屬性。例如誉裆,這段代碼遍歷服務(wù)端的services和 characteristics顿颅,并且將它們顯示在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通知
常見的需求是當(dāng)設(shè)備上的特性改變時通知BLE應(yīng)用程序足丢。這段代碼展示了如何使用 [setCharacteristicNotification()](https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#setCharacteristicNotification(android.bluetooth.BluetoothGattCharacteristic, boolean)) 給一個特性設(shè)置通知粱腻。
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);
一旦對一個特性啟用了通知,當(dāng)遠(yuǎn)程藍(lán)牙設(shè)備特性發(fā)生變化時斩跌,回調(diào)函數(shù)[onCharacteristicChanged( )](http://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html#onCharacteristicChanged(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic))就會被觸發(fā):
@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
關(guān)閉客戶端App
一旦你的app完成了對BLE設(shè)備的使用绍些,需要調(diào)用close()以便系統(tǒng)能適當(dāng)?shù)蒯尫刨Y源:
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
參考鏈接:
https://developer.android.com/guide/topics/connectivity/bluetooth-le.html