個人認為,Android開發后台部分的技術難題只要把google提供的API看懂了就沒什么太多的難點了,關鍵在於運用,藍牙4.0也是,琢磨了好久沒搞懂,結果下了個doc下來自己翻譯一下也就理清了整個過程了,大家可能比較忙,我翻譯一下吧,翻譯得不好別打臉~網上還有很多人的翻譯,我盡量用自己的語言來翻譯,稍微帶點自己的理解。
低功耗藍牙(Bluetooth Low Energy)
Android 4.3 (API Level 18)介紹了一種以低功耗藍牙為核心的開發平台,並提供了可以讓應用程序來發現設備、查詢服務、讀寫特征值等相關API(關於服務、特征值的概念請參考BLE4.0藍牙經典問答,要是不知道可以參考我轉發的一篇,講得很好,藍牙4.0開發人員必看:http://www.cnblogs.com/dbgqp/articles/4103517.html)。 因為低功耗藍牙作為經典藍牙的拓展,相比經典藍牙2.0為了統一通信設備,跟3.0增加數據傳輸速率,4.0盡可能的在降低功耗方面進行了優化。這就允許了android應用程序和低功耗藍牙設備進行通訊,如各類傳感器,心率儀,健身設備等。
關鍵術語和概念
下面是一些主要的BLE的概念性知識:
- Generic Attribute Profile (GATT)—GATT協議是一個通過BLE連接從而發送和接收數據(這種數據格式我們通常稱之為“屬性”)的通用協議。當前所有的低功耗藍牙的應用協議都是基於GATT的。
- 藍牙技術聯盟為低功耗藍牙設備定義了很多協議(我們直接用就行了,so easy,但很重要,大家開發時找准了協議直接下載參考使用就好了,下載地址:https://www.bluetooth.org/en-us/specification/adopted-specifications)。這些協議其實就是個在應用程序中如何在連接的設備中進行通信使用的說明書。每個設備可以使用多個協議,譬如我做的智能硬件就加載了電池電量檢測跟心率監控的協議,用到就加進去就行了,好像我們在Android開發時用的包一樣。
- Attribute Protocol (ATT)—GATT 是ATT的上層架構,GATT把ATT的數據打包成service供我們使用. ATT 運行在我們的藍牙外設設備上.為了達到最優化的目的,它在運行中使用盡可能少的字節。 每個屬性以唯一的UUID(就是把特定的字符串轉換成128位長的數字,通常是16進制的)定義,這個屬性就有ATT進行傳送,我們看到的就是services和characteristics .
- Characteristic—一個 characteristic 包含了一個值和多個描述符。它就好像一個類(可以實例化出一個對象,里面具體的屬性可以由自己定義一樣,不知道這么理解對不對)
- Descriptor—描述符是用來定義屬性的,就像上面講的用來描述characteristic 的(應該想類里面的set 跟get方法一樣的吧)。如指定特征值是否可讀,可接受的范圍或者特征值特定的單位等。
- Service—service是一些列的characteristic 的總集。如你有個服務叫“心率檢測儀”,里面就有個characteristic 叫“心率測量”(應用程序中直接對這個characteristic 的UUID進行數據讀取就行了)。 你可以找到很多基於GATT協議的應用協議,就在上面給的那個網址鏈接中https://www.bluetooth.org/en-us/specification/adopted-specifications。
角色和責任
下面是android手機和BLE設備通信時需要我們注意的一些游戲規則,不遵守的就沒得玩了(中間一段抄的人家的,感覺講得很簡練,可恥地copy了,第一次寫博客,請輕砸):
Central vs. peripheral:
中心設備和外圍設備的概念針對的是BLE連接本身。Central角色負責scan advertisement。而peripheral角色負責make advertisement。
GATT server vs. GATT client:
這兩種角色取決於BLE連接成功后,兩個設備間通信的方式。
舉例說明:
現有一個活動追蹤的BLE設備和一個支持BLE的Android設備。Android設備支持Central角色,而BLE設備支持peripheral角色。創建一個BLE連接需要這兩個角色都存在,都僅支持Central角色或者都僅支持peripheral角色則無法建立連接。
當連接建立后,它們之間就需要傳輸GATT數據。誰做server,誰做client,則取決於具體數據傳輸的情況。例如,如果活動追蹤的BLE設備需要向Android設備傳輸sensor數據,則活動追蹤器自然成為了server端;而如果活動追蹤器需要從Android設備獲取更新信息,則Android設備作為server端可能更合適。
在文件包含的例子中,手機端作為client,從GATT server(一個支持心率協議:https://developer.bluetooth.org/TechnologyOverview/Pages/HRP.aspx的BLE硬件智能設備)中獲取數據,當然,你也可以手動指定你的手機app作為server端,關於BluetoothGattServer可以了解一下:
BLE 權限
廢話不多說,你要想在手機里使用藍牙的功能你就得申明藍牙的使用權限:BLUETOOTH,你需要這個權限來完成各種藍牙通信,如請求連接,接受連接,收發數據。
如果你想要你的APP發起設備發現或者修改藍牙設置,你必須要申明:BLUETOOTH_ADMIN權限。不過你想要用該權限那必須先得擁有BLUETOOTH的權限。
在manifest 文件中申明權限的方法:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
如果你想讓你的應用程序只在低功耗藍牙手機上工作,那你可以如下設置:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
然而,如果你想讓你的應用程序同樣可以在不支持藍牙4.0的設備上工作的話,你也應該申明上述權限,但要set required="false". 然后在程序運行過程中你可以通過PackageManager.hasSystemFeature()來申明低功耗藍牙是否可用。
// 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();
}
下面就簡單了,主要是低功耗藍牙的代碼開發步驟,大家隨便看看,然后把官網提供的范例下載下來學習一下,范例只有讀,沒有寫,大家百度一下就可以找到,。
找不到的再問我要吧:至於我自己開發的項目中的一些功能我到時看看稍微修改一下放出來讓大家也幫忙指導一下,這個博客我還不會上傳附件。
需要的問我QQ:772026483要吧,QQ不在可以到我微博上留郵箱:微博VIA:逗不過奇葩;
鑒於本人不是專業的android開發工程師,大家太高深的問題就別問了,只是項目中需要才研究做個android APP的。
步驟開始
設置藍牙
在你應用程序通過低功耗藍牙通訊前,你需要query你的設備是否支持BLE,確保它是可用的。注意:這個檢查只有在<uses-feature.../>中set to false的時候才是必須做的。
如果BLE不支持,那你就沒辦法使用BLE的功能咯。如果支持BLE,但沒有開啟藍牙功能,你可以請求使用者在你的應用程序中開啟。設置藍牙可以通過BluetoothAdapter分兩步完成:
幾乎所有的藍牙activity都需要 BluetoothAdapter . BluetoothAdapter 代表了設備自身的藍牙適配器。在整個系統中只有一個藍牙適配器,你的應用程序可以通過BluetoothAdapter使用它,下面的代碼演示了如何獲取適配器。注意:該方法是通過getSystemService返回的一個BluetoothManager實例來得到適配器,關於BluetoothManager在Android 4.3 (API Level 18)中有詳細介紹。
// Initializes Bluetooth adapter.初始化藍牙適配器
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
- 啟動藍牙
下一步,你需要確定藍牙是可用的,調用isEnabled()來檢測藍牙當前狀態是否可用,如果返回false,當前藍牙不可用。下面的代碼演示了如何檢測是否可用,如果不可用,則設置開啟藍牙
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藍牙設備
你可以使用startLeScan()方法來發現BLE設備,該方法用BluetoothAdapter.LeScanCallback作為參數,你必須繼承這個回調來獲取掃描結果,由於掃描過程很耗電,你應該遵守以下的引導來降低功耗:
- 一旦發現目標設備立刻停止掃描.
- 不要重復掃描,設置一個i額掃描時間限制,以前連接的設備可能已經離開了當前可掃描的范圍,持續掃描會增加功耗。
下面代碼演示了如何發起和停止掃描:
/**
* 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)這個方法來代替上面代碼的掃描函數。該方法中的UUID就是你app中支持的服務的UUIP,在搜索過程中就進行了一遍篩選連接。
下面的代碼是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();
}
});
}
};
注意: 搜索時,你只能搜索傳統藍牙設備或者BLE設備,兩者完全獨立,不可同時被搜索.
連接到一個GATT server
兩個設備通過BLE通信,首先需要建立GATT連接。這里我們講的是Android設備作為client端,連接GATT Server。
連接GATT Server,你需要調用BluetoothDevice的connectGatt()方法。此函數帶三個參數:Context、autoConnect(boolean來表明當BLE設備可用時是否主動去連接它)和BluetoothGattCallback對象。調用示例:
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
函數成功,返回BluetoothGatt對象,它是GATT profile的封裝。通過這個對象,我們就能進行GATT Client端(就是我們手機端的APP)的相關操作。BluetoothGattCallback用於傳遞一些連接狀態及結果給client端。
在該實例中,app提供了一個DeviceControlActivity來連接,顯示數據,並列出了由設備提供的服務和特征,基於用戶的輸入,這個activity通過Android BLE API來調用BluetoothLeService和service通訊。
// 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()方法並給它發一個動作,下面這段是Bluetooth Heart Rate Measurement profile 中的實現代碼,可以參考了解一下:
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屬性(數據)
一旦你的APP連接到了一個GATT server並且發現相關的服務(serices),它就可以根讀寫服務中提供的屬性(參考上面的概念);
下面的代碼演示了如何把搜索到的可用的服務和特征遍歷顯示在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的APP就會收到通知。
下面的代碼演示了如何通過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);
Once notifications are enabled for a characteristic, an onCharacteristicChanged() callback is triggered if the characteristic changes on the remote device:
@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
關閉client的APP:
一旦你的APP結束使用BLE設備,它需要調用close()來讓系統適當的回收資源和釋放內存空間。
示例代碼:
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
摘抄的人家的一段,算是備注一下:
BluetoothGatt常規用到的幾個操作示例:
connect() :連接遠程設備。
discoverServices() : 搜索連接設備所支持的service。
disconnect():斷開與遠程設備的GATT連接。
close():關閉GATT Client端。
readCharacteristic(characteristic) :讀取指定的characteristic。
setCharacteristicNotification(characteristic, enabled) :設置當指定characteristic值變化時,發出通知。
getServices() :獲取遠程設備所支持的services。
等等。
注:
1、某些函數調用之間存在先后關系。例如首先需要connect上才能discoverServices。
2、一些函數調用是異步的,需要得到的值不會立即返回,而會在BluetoothGattCallback的回調函數中返回。例如discoverServices與onServicesDiscovered回調,readCharacteristic與onCharacteristicRead回調,setCharacteristicNotification與onCharacteristicChanged回調等。
本文中除了自己理解的部分外,參考的博客地址是:http://www.blogjava.net/zh-weir/archive/2013/12/09/407373.html
自己翻譯前大概瀏覽過《低功耗藍牙開發權威指南》跟《藍牙4.0BLE開發完全手冊》,這兩本書很實用,可惜沒時間好好看,推薦給大家!