安卓BLE开发教程(二) BLE开发流程
在安卓上進(jìn)行BLE開(kāi)發(fā)時(shí),就不必像理解BLE協(xié)議棧那樣復(fù)雜了。因?yàn)榘沧康腂LE包為我們提供了十分豐富的API、各類常量、各類連接通信情況下的回調(diào)API等。
具體流程
一、聲明權(quán)限
二、獲取Adapter適配器
三、開(kāi)啟藍(lán)牙
四、BLE掃描與停止
五、連接設(shè)備
六、枚舉特征值及其屬性
七、利用特征值通訊
八、關(guān)閉藍(lán)牙
一、聲明權(quán)限
在AndroidManifest.xml文件中聲明應(yīng)用需要的特性及權(quán)限。
<!-- 聲明App使用條件為支持BLE --> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/> <!-- 聲明藍(lán)牙權(quán)限 --> <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <!-- 安卓6.0開(kāi)始需要此權(quán)限 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>二、獲取Adapter適配器
final BluetoothManager mBluetoothManager =(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();三、開(kāi)啟藍(lán)牙
if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(intent, BLE_ENABLE); }四、BLE掃描與停止
private boolean mScanning;//是否正在搜索 private Handler mHandler = new Handler(); // 預(yù)設(shè)15秒掃描時(shí)間 private static final int SCAN_PERIOD = 15000;private void scanLeDevice(final boolean enable) {if (enable) {// 控制BLE掃描時(shí)間mHandler.postDelayed(new Runnable() {@Overridepublic void run() {mBluetoothAdapter.stopLeScan(mLeScanCallback);}}, SCAN_PERIOD);mScanning = true;// 開(kāi)始掃描mBluetoothAdapter.startLeScan(mLeScanCallback);} else {mScanning = false;// 停止掃描mBluetoothAdapter.stopLeScan(mLeScanCallback);} }在BLE掃描回調(diào)函數(shù)中保存設(shè)備對(duì)應(yīng)的BlueToothDevice對(duì)象,rssi信號(hào)強(qiáng)度等。
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {@Overridepublic void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {// 保存device及相關(guān)信息,也可以通知UI線程顯示信息}};五、連接設(shè)備
使用掃描結(jié)果中保存的BluetoothDevice對(duì)象調(diào)用connectGatt進(jìn)行通訊。
BluetoothGatt mBluetoothGatt; // 參數(shù)一:context上下文 // 參數(shù)二:是否自動(dòng)重連 // 參數(shù)三: 連接回調(diào) mBluetoothGatt = mBluetoothDevice.connectGatt(context, false, mGattCallback);連接回調(diào)函數(shù)實(shí)現(xiàn)如下,開(kāi)發(fā)時(shí)在此處處理各類可能遇到的情況。
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {// 連接狀態(tài)改變的回調(diào)@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status,int newState) {// 具體處理見(jiàn)后文第八項(xiàng)};// 發(fā)現(xiàn)服務(wù)回調(diào)@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {// 具體處理見(jiàn)后文第六項(xiàng)};@Overridepublic void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {// 由mBluetoothGatt.readRemoteRssi()調(diào)用得到,可不停刷新rssi信號(hào)強(qiáng)度Log.e(TAG, "信號(hào)強(qiáng)度RSSI:" + rssi);}// 寫描述信息回調(diào)@Overridepublic void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptordescriptor, int status) {};// 寫操作回調(diào)@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {Log.e(TAG, "寫入成功:" + characteristic.getValue());}};// 讀操作回調(diào)@Overridepublic void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {Log.e(TAG, "讀取成功:" + characteristic.getValue());}}// 數(shù)據(jù)改變回調(diào)(接收BLE設(shè)備發(fā)送的數(shù)據(jù))@Overridepublic void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {};}; }六、枚舉特征值及其屬性
@Override // 發(fā)現(xiàn)服務(wù)回調(diào),即調(diào)用了mBluetoothGatt.discoverServices()執(zhí)行的回調(diào) public void onServicesDiscovered(BluetoothGatt gatt, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {// 獲取ServiceList<BluetoothGattService> mGattServices = gatt.getServices();// 獲取Service的Characteristicsfor (BluetoothGattService gattService : mGattServices) {List<BluetoothGattCharacteristic> mGattCharacteristics = gattService.getCharacteristics();for (BluetoothGattCharacteristic gattCharacteristic :mGattCharacteristics) {int charaProp = gattCharacteristic.getProperties();// 所有Characteristics按屬性分類if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {Log.e(TAG, "gattCharacteristic的UUID為:" + gattCharacteristic.getUuid());Log.e(TAG, "gattCharacteristic的屬性為:可讀");readUuids.add(gattCharacteristic.getUuid());}if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {Log.e(TAG, "gattCharacteristic的UUID為:" + gattCharacteristic.getUuid());Log.e(TAG, "gattCharacteristic的屬性為:可寫");writeUuids.add(gattCharacteristic.getUuid());}if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {Log.e(TAG, "gattCharacteristic的UUID為:" + gattCharacteristic.getUuid() + gattCharacteristic);Log.e(TAG, "gattCharacteristic的屬性為:具備通知屬性");notifyUuids.add(gattCharacteristic.getUuid());}}}} else {Log.e(TAG, "onServicesDiscovered 失敗,status:" + status);} }七、利用特征值通訊
1、寫數(shù)據(jù)
public void writeChara(byte) {BluetoothGattCharacteristic mGattCharacteristic = mBluetoothGatt.getCharacteristic(writeUuid);mGattCharacteristic.setValue(sendValue);mBluetoothGatt.writeCharacteristic(mGattCharacteristic); }2、讀數(shù)據(jù)
public void readChara() {// 讀取數(shù)據(jù)BluetoothGattCharacteristic mGattCharacteristic = mBluetoothGatt.getCharacteristic(readUuid);mBluetoothGatt.readCharacteristic(mGattCharacteristic); }3、監(jiān)聽(tīng)通知屬性的數(shù)據(jù)
mBluetoothGatt.setCharacteristicNotification(mGattCharacteristic, enabled); BluetoothGattDescriptor mGattDescriptor = mGattCharacteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG)); mGattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mBluetoothGatt.writeDescriptor(mGattDescriptor);八、關(guān)閉藍(lán)牙
合理的關(guān)閉步驟為,先調(diào)用BluetoothGatt#disconnect進(jìn)行斷開(kāi)連接,此時(shí)會(huì)在BluetoothGattCallback#onConnectionStateChange接收到斷開(kāi)成功的回調(diào),然后在回調(diào)中調(diào)用BluetoothGatt#close釋放相關(guān)資源。
// 首先執(zhí)行該disconnect操作,然后等待回調(diào)通知 mBluetoothGatt.disconnect(); @Override public void onConnectionStateChange(BluetoothGatt gatt, int status,int newState) {if (newState != BluetoothGatt.GATT_SUCCESS) {// 連接失敗直接在此處理即可,因此時(shí)調(diào)用disconnect無(wú)法進(jìn)入下面條件Log.e(TAG, "連接失敗, status:" + status);gatt.close();return;}if (newState == BluetoothGatt.STATE_DISCONNECTED) {// 連接斷開(kāi)Log.e(TAG, "連接斷開(kāi)");mBluetoothGatt.close();} else if (newState == BluetoothProfile.STATE_CONNECTED) {// 連接成功后啟動(dòng)服務(wù)發(fā)現(xiàn)Log.e(TAG, "連接成功");mBluetoothGatt.discoverServices();} };?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的安卓BLE开发教程(二) BLE开发流程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何在Windows Server 20
- 下一篇: Jenkins配置Findbugs做源代