一旗扑、方法
- 使用開源庫fastble
- 使用開源庫baseble
- 使用原生接口
二膨处、聲明權限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
如果您要聲明您的應用僅適用于支持 BLE 的設備,請在應用清單中添加以下內(nèi)容:
<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 disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
●android.permission.BLUETOOTH
: 這個權限允許程序連接到已配對的藍牙設備, 請求連接/接收連接/傳輸數(shù)據(jù)需要改權限, 主要用于對配對后進行操作;
●android.permission.BLUETOOTH_ADMIN
: 這個權限允許程序發(fā)現(xiàn)和配對藍牙設備, 該權限用來管理藍牙設備, 有了這個權限, 應用才能使用本機的藍牙設備, 主要用于對配對前的操作;
●android.permission.ACCESS_COARSE_LOCATION
和android.permission.ACCESS_FINE_LOCATION
:Android 6.0以后安聘,這兩個權限是必須的痰洒,藍牙掃描周圍的設備需要獲取模糊的位置信息。這兩個權限屬于同一組危險權限浴韭,在清單文件中聲明之后丘喻,還需要再運行時動態(tài)獲取。
- Android 6.0以上獲取位置權限代碼如下:
//判斷是否為android6.0系統(tǒng)版本念颈,如果是泉粉,需要動態(tài)添加權限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//獲取權限(如果沒有開啟權限,會彈出對話框舍肠,詢問是否開啟權限)
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//請求權限
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, R.id.request_code_local);
}
}
三搀继、關于BLE和Android原生接口的使用
Android 4.3(Api Level18)引入BLE支持
BLE關鍵術語和概念
通用屬性配置文件 (GATT)
GATT配置文件是一種通用規(guī)范,內(nèi)容針對在BLE鏈路上發(fā)送和接收稱為“屬性”的簡短數(shù)據(jù)片段翠语。目前所有低功耗應用配置文件都是以GATT為基礎叽躯。
藍牙特別興趣小組 (Bluetooth SIG) 為低功耗設備定義諸多配置文件。配置文件是描述設備如何在特定應用中工作的規(guī)范肌括。請注意点骑,一臺設備可以實現(xiàn)多個配置文件酣难。例如,一臺設備可能包含心率監(jiān)測儀和電池電量檢測器黑滴。屬性協(xié)議 (ATT)
屬性協(xié)議 (ATT) 是 GATT 的構建基礎憨募,二者的關系也被稱為 GATT/ATT。ATT 經(jīng)過優(yōu)化袁辈,可在 BLE 設備上運行菜谣。為此,該協(xié)議盡可能少地使用字節(jié)晚缩。每個屬性均由通用唯一標識符 (UUID) 進行唯一標識尾膊,后者是用于對信息進行唯一標識的字符串 ID 的 128 位標準化格式。由 ATT 傳輸?shù)膶傩圆捎锰卣骱头崭袷健?/p>特征
特征包含一個值和 0 至多個描述特征值的描述符荞彼。您可將特征理解為類型冈敛,后者與類類似。描述符
描述符是描述特征值的已定義屬性鸣皂。例如抓谴,描述符可指定人類可讀的描述、特征值的可接受范圍或特定于特征值的度量單位Service
服務是一系列特征寞缝。例如癌压,您可能擁有名為“心率監(jiān)測器”的服務,其中包括“心率測量”等特征第租。您可以在 bluetooth.org 上找到基于 GATT 的現(xiàn)有配置文件和服務的列表措拇。
角色和職責
以下是 Android 設備與 BLE 設備交互時應用的角色和職責:
中央(Central)與外圍(Peripheral)。這適用于 BLE 連接本身慎宾。擔任中央角色的設備進行掃描丐吓、尋找廣播;外圍設備發(fā)出廣播趟据。詳細可看鏈接:BLE設備角色
GATT 服務器與 GATT 客戶端券犁。這確定兩個設備建立連接后如何相互通信。
設置BLE
如果不支持 BLE汹碱,則應妥善停用任何 BLE 功能粘衬。如果設備支持 BLE 但已停用此功能,則您可以請求用戶在不離開應用的同時啟用藍牙咳促。借助 BluetoothAdapter稚新,您可以分兩步完成此設置。
- 獲取 BluetoothAdapter
所有藍牙 Activity 都需要 BluetoothAdapter跪腹。BluetoothAdapter 代表設備自身的藍牙適配器(藍牙無線裝置)褂删。整個系統(tǒng)有一個藍牙適配器,并且您的應用可使用此對象與之進行交互冲茸。以下代碼段展示如何獲取適配器屯阀。請注意缅帘,此方法使用 getSystemService()返回 BluetoothManager的實例,然后使用該實例獲取適配器难衰。Android 4.3(API 級別 18)引入 BluetoothManager:
private BluetoothAdapter bluetoothAdapter;
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
- 啟用藍牙
下一步钦无,您需要確保藍牙已啟用。調(diào)用 isEnabled()盖袭,以檢查當前是否已啟用藍牙失暂。如果此方法返回 false,則表示藍牙處于停用狀態(tài)苍凛。以下代碼段會檢查藍牙是否已啟用趣席。如果并未啟用,則代碼段會顯示錯誤醇蝴,提示用戶前往“Settings”啟用藍牙:
// 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
常量是本地定義的整數(shù)(必須大于0),系統(tǒng)會在您的 onActivityResult(int, int, android.content.Intent)實現(xiàn)中將其作為requestCode
參數(shù)傳回給您想罕。
查找設備
如要查找 BLE 設備悠栓,請使用 startLeScan() 方法。此方法將 BluetoothAdapter.LeScanCallback作為參數(shù)按价。您必須實現(xiàn)此回調(diào)惭适,因為這是返回掃描結果的方式。掃描非常耗電楼镐,因此您應遵循以下準則:
- 找到所需設備后癞志,立即停止掃描。
- 絕對不進行循環(huán)掃描框产,并設置掃描時間限制凄杯。之前可用的設備可能已超出范圍,繼續(xù)掃描會耗盡電池電量秉宿。
以下代碼段展示如何啟動和停止掃描:
/**
* Activity for scanning and displaying available BLE devices.
*/
public class DeviceScanActivity extends ListActivity {
private BluetoothAdapter bluetoothAdapter;
private boolean mScanning = false;
private Handler handler = new 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);
}
...
}
...
}
如果您想掃描特定類型的外圍設備戒突,則可調(diào)用 startLeScan(UUID[], BluetoothAdapter.LeScanCallback),它會提供一組 UUID對象描睦,用于指定您的應用支持的 GATT 服務膊存。
以下是 BluetoothAdapter.LeScanCallback的實現(xiàn),其為用于傳遞 BLE 掃描結果的界面:
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();
}
});
}
};
本人使用設備Android9.0 使用獲取設備廣播包的代碼如下
- 創(chuàng)建回調(diào)函數(shù)和定時器
private ScanCallback cl = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
Log.d(LOG_TAG, "device " + result.getDevice().getAddress().replace(":", ""));
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
for (ScanResult ret : results) {
Log.d(LOG_TAG, "result " + ret.toString());
}
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Toast.makeText(mActivity, "Scan failed with error: " + errorCode, Toast.LENGTH_LONG).show();
}
};
private Runnable runnable = new Runnable() {
@Override
public void run() {
mScanning = false;
bluetoothAdapter.getBluetoothLeScanner().stopScan(cl );
}
};
- 開始和停止掃描設備(添加和移除回調(diào)函數(shù))
private void scanLeDevice(boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
handler.postDelayed(runnable, SCAN_PERIOD);
mScanning = true;
bluetoothAdapter.getBluetoothLeScanner().startScan(cl);
} else {
mScanning = false;
handler.removeCallbacks(runnable);
bluetoothAdapter.getBluetoothLeScanner().stopScan(cl);
}
}
注意:僅能掃描藍牙 LE 設備或傳統(tǒng)藍牙設備忱叭,正如藍牙概覽中所述隔崎。無法同時掃描藍牙 LE 設備和傳統(tǒng)藍牙設備
連接到GATT服務器
與 BLE 設備交互的第一步便是連接到 GATT 服務器。更具體地說韵丑,是連接到設備上的 GATT 服務器爵卒。如要連接到 BLE 設備上的 GATT 服務器,請使用 connectGatt()方法埂息。此方法采用三個參數(shù):一個 Context 對象技潘、autoConnect
(布爾值遥巴,指示是否在可用時自動連接到 BLE 設備),以及對 BluetoothGattCallback 的引用:
bluetoothGatt = device.connectGatt(this, false, gattCallback);
這將連接到由 BLE 設備托管的 GATT 服務器享幽,并返回 BluetoothGatt實例铲掐,然后您可使用該實例執(zhí)行 GATT 客戶端操作。調(diào)用方(Android 應用)是 GATT 客戶端值桩。BluetoothGattCallback用于向客戶端傳遞結果(例如連接狀態(tài))摆霉,以及任何進一步的 GATT 客戶端操作。
在本例中奔坟,BLE 應用提供一個 Activity (DeviceControlActivity
) 來連接携栋、顯示數(shù)據(jù)和顯示設備支持的 GATT 服務和特征。根據(jù)用戶輸入咳秉,此 Activity 和一個名為 BluetoothLeService
的 Service 通信婉支,該服務通過 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 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);
}
}
...
};
...
}
當一個特定回調(diào)被觸發(fā)時,它會調(diào)用相應的 broadcastUpdate()
輔助方法并向其傳遞操作澜建。請注意向挖,本部分的數(shù)據(jù)解析參照“藍牙心率測量”配置文件規(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 應用成功連接到 GATT 服務器并發(fā)現(xiàn)服務后炕舵,應用便可在支持的位置讀取和寫入屬性何之。例如,以下代碼段遍歷服務器的服務和特征咽筋,并在界面中將其顯示出來:
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 應用通常會要求在設備上的特定特征發(fā)生變化時收到通知溶推。以下代碼段展示如何使用 setCharacteristicNotification()方法設置特征的通知:
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);
為某個特征啟用通知后,如果遠程設備上的特征發(fā)生更改奸攻,則會觸發(fā) onCharacteristicChanged() 回調(diào):
@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
關閉客戶端應用
當應用完成對 BLE 設備的使用后蒜危,其應調(diào)用 close(),以便系統(tǒng)可以適當?shù)蒯尫刨Y源:
public void close() {
if (bluetoothGatt == null) {
return;
}
bluetoothGatt.close();
bluetoothGatt = null;
}