分享Android 藍(lán)牙4.0(ble)開發(fā)的解決方案
最近,隨著智能穿戴式設(shè)備、智能醫(yī)療以及智能家居的普及,藍(lán)牙開發(fā)在移動(dòng)開中顯得非常的重要。由于公司需要,研究了一下,藍(lán)牙4.0在Android中的應(yīng)用。
以下是我的一些總結(jié)。
1.先介紹一下關(guān)于藍(lán)牙4.0中的一些名詞吧:
(1)、GATT(Gneric Attibute Profile)
通過ble連接,讀寫屬性類小數(shù)據(jù)Profile通用的規(guī)范。現(xiàn)在所有的ble應(yīng)用Profile 都是基于GATT
(2)、ATT(Attribute Protocal)
GATT是基于ATT Potocal的ATT針對(duì)BLE設(shè)備專門做的具體就是傳輸過程中使用盡量少的數(shù)據(jù),每個(gè)屬性都有個(gè)唯一的UUID,屬性chartcteristics and Service的形式傳輸。
(3)、Service是Characteristic的集合。
(4)、Characteristic 特征類型。
比如,有個(gè)藍(lán)牙ble的血壓計(jì)。他可能包括多個(gè)Servvice,每個(gè)Service有包括多個(gè)Characteristic
注意:藍(lán)牙ble只能支持Android 4.3以上的系統(tǒng) SDK>=18
2.以下是開發(fā)的步驟:
2.1首先獲取BluetoothManager
2.2獲取BluetoothAdapter
2.3創(chuàng)建BluetoothAdapter.LeScanCallback
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
String struuid = NumberUtils.bytes2HexString(NumberUtils.reverseBytes(scanRecord)).replace("-", "").toLowerCase();
if (device!=null && struuid.contains(DEVICE_UUID_PREFIX.toLowerCase())) {
mBluetoothDevices.add(device);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
2.4.開始搜索設(shè)備。
2.5.BluetoothDevice 描述了一個(gè)藍(lán)牙設(shè)備 提供了getAddress()設(shè)備Mac地址,getName()設(shè)備的名稱。
2.6開始連接設(shè)備
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* @param address
* The device address of the destination device.
*
* @return Return true if the connection is initiated successfully. The
* connection result is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect. (先前連接的設(shè)備。 嘗試重新連接)
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the
// autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
2.7連接到設(shè)備之后獲取設(shè)備的服務(wù)(Service)和服務(wù)對(duì)應(yīng)的Characteristic。
// 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;
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<>();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<>();
mGattCharacteristics = new ArrayList<>();
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
HashMap<String, String> currentServiceData = new HashMap<>();
uuid = gattService.getUuid().toString();
if (uuid.contains("ba11f08c-5f14-0b0d-1080")) {//服務(wù)的uuid
//System.out.println("this gattService UUID is:" + gattService.getUuid().toString());
currentServiceData.put(LIST_NAME, "Service_OX100");
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<>();
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<>();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<>();
uuid = gattCharacteristic.getUuid().toString();
if (uuid.toLowerCase().contains("cd01")) {
currentCharaData.put(LIST_NAME, "cd01");
} else if (uuid.toLowerCase().contains("cd02")) {
currentCharaData.put(LIST_NAME, "cd02");
} else if (uuid.toLowerCase().contains("cd03")) {
currentCharaData.put(LIST_NAME, "cd03");
} else if (uuid.toLowerCase().contains("cd04")) {
currentCharaData.put(LIST_NAME, "cd04");
} else {
currentCharaData.put(LIST_NAME, "write");
}
currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
}
mGattCharacteristics.add(charas);
gattCharacteristicData.add(gattCharacteristicGroupData);
mCharacteristicCD01 = gattService.getCharacteristic(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD02 = gattService.getCharacteristic(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD03 = gattService.getCharacteristic(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD04 = gattService.getCharacteristic(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"));
mCharacteristicWrite = gattService.getCharacteristic(UUID.fromString("0000cd20-0000-1000-8000-00805f9b34fb"));
//System.out.println("=======================Set Notification==========================");
// 開始順序監(jiān)聽,第一個(gè):CD01
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD01, true);
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD02, true);
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD03, true);
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD04, true);
}
}
}
2.8獲取到特征之后,找到服務(wù)中可以向下位機(jī)寫指令的特征,向該特征寫入指令。
public void wirteCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.writeCharacteristic(characteristic);
}
2.9寫入成功之后,開始讀取設(shè)備返回來的數(shù)據(jù)。
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
//System.out.println("=======status:" + status);
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
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
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
//從特征中讀取數(shù)據(jù)
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//System.out.println("onCharacteristicRead");
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
//向特征中寫入數(shù)據(jù)
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//System.out.println("--------write success----- status:" + status);
}
/*
* when connected successfully will callback this method this method can
* dealwith send password or data analyze
*當(dāng)連接成功將回調(diào)該方法
*/
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
if (characteristic.getValue() != null) {
//System.out.println(characteristic.getStringValue(0));
}
//System.out.println("--------onCharacteristicChanged-----");
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
//System.out.println("onDescriptorWriteonDescriptorWrite = " + status + ", descriptor =" + descriptor.getUuid().toString());
UUID uuid = descriptor.getCharacteristic().getUuid();
if (uuid.equals(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD01NOTIDIED);
} else if (uuid.equals(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD02NOTIDIED);
} else if (uuid.equals(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD03NOTIDIED);
} else if (uuid.equals(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD04NOTIDIED);
}
}
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
//System.out.println("rssi = " + rssi);
}
};
----------------------------------------------
//從特征中讀取數(shù)據(jù)
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//System.out.println("onCharacteristicRead");
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
2.10、斷開連接
/**
* Disconnects an existing connection or cancel a pending connection. The
* disconnection result is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
2.11、數(shù)據(jù)的轉(zhuǎn)換方法
// byte轉(zhuǎn)十六進(jìn)制字符串
public static String bytes2HexString(byte[] bytes) {
String ret = "";
for (byte aByte : bytes) {
String hex = Integer.toHexString(aByte & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase(Locale.CHINA);
}
return ret;
}
/**
* 將16進(jìn)制的字符串轉(zhuǎn)換為字節(jié)數(shù)組
*
* @param message
* @return 字節(jié)數(shù)組
*/
public static byte[] getHexBytes(String message) {
int len = message.length() / 2;
char[] chars = message.toCharArray();
String[] hexStr = new String[len];
byte[] bytes = new byte[len];
for (int i = 0, j = 0; j < len; i += 2, j++) {
hexStr[j] = "" + chars[i] + chars[i + 1];
bytes[j] = (byte) Integer.parseInt(hexStr[j], 16);
}
return bytes;
}
大概整體就是如上的步驟,但是也是要具體根據(jù)廠家的協(xié)議來實(shí)現(xiàn)通信的過程。
就拿一個(gè)我們項(xiàng)目中的demo說一下。
一個(gè)藍(lán)牙ble的血壓計(jì)。 上位機(jī)---手機(jī) 下位機(jī) -- 血壓計(jì)
1.血壓計(jì)與手機(jī)連接藍(lán)牙之后。
2.上位機(jī)主動(dòng)向下位機(jī)發(fā)送一個(gè)身份驗(yàn)證指令,下位機(jī)收到指令后開始給上位做應(yīng)答,
3.應(yīng)答成功,下位機(jī)會(huì)將測(cè)量的血壓數(shù)據(jù)傳送到上位機(jī)。
4.最后斷開連接。
希望本文對(duì)大家學(xué)習(xí)Android藍(lán)牙技術(shù)有所幫助。
- Android藍(lán)牙開發(fā)深入解析
- 詳解Android——藍(lán)牙技術(shù) 帶你實(shí)現(xiàn)終端間數(shù)據(jù)傳輸
- Android單片機(jī)與藍(lán)牙模塊通信實(shí)例代碼
- Android Bluetooth藍(lán)牙技術(shù)使用流程詳解
- Android 獲取藍(lán)牙Mac地址的正確方法
- Android手機(jī)通過藍(lán)牙連接佳博打印機(jī)的實(shí)例代碼
- android實(shí)現(xiàn)藍(lán)牙文件發(fā)送的實(shí)例代碼,支持多種機(jī)型
- Android實(shí)現(xiàn)藍(lán)牙(BlueTooth)設(shè)備檢測(cè)連接
- 詳解Android 藍(lán)牙通信方式總結(jié)
- Android學(xué)習(xí)筆記之藍(lán)牙功能
相關(guān)文章
Activity跳轉(zhuǎn)時(shí)生命周期跟蹤的實(shí)例
下面小編就為大家?guī)硪黄狝ctivity跳轉(zhuǎn)時(shí)生命周期跟蹤的實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-03-03
Android編程自定義title bar(標(biāo)題欄)示例
這篇文章主要介紹了Android編程自定義title bar(標(biāo)題欄)的方法,結(jié)合實(shí)例形式分析了Android針對(duì)標(biāo)題欄的設(shè)置與頁面布局操作相關(guān)技巧,需要的朋友可以參考下2016-10-10
Flutter實(shí)現(xiàn)不同縮放動(dòng)畫效果詳解
這篇文章主要為大家詳細(xì)介紹了Flutter利用不同組件(ScaleTransition、SizeTransition、AnimatedSize和AnimatedBuilder)實(shí)現(xiàn)不同縮放動(dòng)畫效果,感興趣的可以動(dòng)手嘗試一下2022-06-06
Android編程下拉菜單spinner用法小結(jié)(附2則示例)
這篇文章主要介紹了Android編程下拉菜單spinner用法,結(jié)合實(shí)例較為詳細(xì)的總結(jié)分析了下拉菜單Spinner的具體實(shí)現(xiàn)步驟與相關(guān)技巧,并附帶兩個(gè)示例分析其具體用法,需要的朋友可以參考下2015-12-12
解決android viewmodel 數(shù)據(jù)刷新異常的問題
這篇文章主要介紹了解決android viewmodel 數(shù)據(jù)刷新異常的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03

