Android Bluetooth Low Energy(Android低功耗藍芽)

來源:互聯網
上載者:User

標籤:android   bluetooth   ble   藍芽   低功耗   


Android 4.3(API Level 18)開始引入Bluetooth Low Energy(BLE,低功耗藍芽)的核心功能並提供了相應的API,應用程式通過這些api可以掃描裝置、查詢services,讀寫裝置的characteristics(屬性特徵)。對比傳統的藍芽,BLE的設計能夠顯著減低功耗。這讓Android應用程式與BLE裝置之間的低功耗通訊成為可能,例如距離感應器、心率監測器、健身裝置等等。


1、關鍵術語和概念
1.1 下面是一些BLE關鍵術語和概念的摘要:

* Generic Attribute Profile(GATT):GATT profile是一種關於發送和接收簡短資料片段的一般規範,這種簡短資料片段例如在BLE的串連上眾所周知的“attribute(屬性)”等。當前所有低功耗應用程式的profile都基於GATT。另外,藍芽技術聯盟(Bluetooth SIG)已經為很多BLE裝置定義了profile。profile就是一種在指定的應用程式中定義裝置如何工作的規範。注意,一台裝置可以實現多個profile。例如,一台裝置可以包含心率監測器和電池電量探測器。
* Attribute Protocol(ATT,屬性協議):GATT構建在ATT的基礎之上,因此也總被成為GATT/ATT。ATT針對BLE裝置的運行進行了最佳化。為此,它會儘可能的使用更少的位元組資料。每一個屬性都通過UUID來唯一確定。UUID就是一個標準128位格式的字串ID,用於唯一確定一個資訊。屬性通過ATT協議格式化為characteristics和services後進行傳輸。
* Characteristic:一個characteristic中包含一個值,以及0個或多個用於描述characteristic值的descriptor。可以將characteristic認為是一種類型,類似於一個類。
* Descriptor:Descriptor(描述符)中定義的屬性用於描述一個characteristic值。例如,一個descriptor可以為一個characteristic的值指定一個在可接受範圍內的可讀性描述,或者為一個characteristic的值指定一個計量單位。
* Service:
一個service是一個characteristic的集合。例如,你可以持有一個名為“心率監測器”的service,它包含的characteristic例如“心率測量”。你可以在bluetooth.org上找到一系列基於GATT的profile和service。


1.2 角色和職能

以下是一台Android裝置與BLE裝置互動時的一些適用角色和職能:

* 中央裝置和外圍裝置。這適用於BLE自身的串連。擔任中央裝置角色的裝置負責掃描和搜尋廣告,擔任外圍裝置的角色負責發送廣告。

* GATT服務端和GATT用戶端。這取決於兩台裝置在建立串連後如何互相通訊。


為了理解這之間的區別,想象你有一台Android手機和一台BLE裝置作為活動追蹤器。手機將擔任中央裝置角色;活動追蹤器將擔任外圍裝置角色(你需要具備兩種角色才能建立一個BLE串連,兩者都擔任外圍裝置角色不能互相通訊,同樣兩者都擔任中央裝置角色也不能互相通訊)。


一旦手機和活動追蹤器建立串連,它們就可以互相傳輸GATT媒體資料。根據它們傳輸的資料,其中一方需要擔任服務端的角色。例如,如果活動追蹤器想要發送感應器資料給手機,活動追蹤器就需要擔任服務端的角色。如果活動追蹤器想要接收手機的資料,手機就需要擔任服務端的角色。


在本片文檔的例子中,Android應用程式(運行在Android裝置上)是GATT用戶端。應用程式從GATT服務端擷取資料,這個服務端由支援Heart Rate Profile的BLE心率監測器裝置擔任。但是你可以交替讓你的Android應用程式扮演GATT服務端的角色。具體參考BluetoothGattService。


2、BLE Permissions(BLE許可權)

為了在你的應用程式中使用Bluetooth的功能,你必須聲明android.permission.BLUETOOTH許可權。你需要這個許可權來執行一些藍芽通訊的操作,例如請求連結,接受串連,還有傳輸資料。


如果你想讓你的應用程式進行裝置掃描或者管理藍芽設定,你必須同時聲明android.permission.BLUETOOTH_ADMIN許可權。注意,如果你使用BLUETOOTH_ADMIN許可權,你必須同時聲明BLUETOOTH許可權。


在你的應用程式manifest檔案中聲明藍芽許可權,例如:

<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

如果你想聲明你的應用程式只能在支援BLE的裝置上運行,可以將下面聲明包含進你的應用程式manifest檔案中:

<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

然而,如果你想讓你的應用程式也能夠在不支援BLE的裝置上運行,你就應該將上面標籤中的屬性設定為required="false"。然後在啟動並執行過程中使用PackageManager.hasSystemFeature()方法來判斷裝置是否支援BLE:

// 使用下面的方法來確定裝置是否支援BLE, 然後你可以選擇禁用BLE的功能if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();    finish();}

3、Setting Up BLE(設定BLE)

在你的應用程式通過BLE進行通訊之前,你需要確認裝置是否支援BLE。如果支援,還要再確認是否已經啟用。注意這個檢查步驟只有在<uses-festure.../>設定為false的情況下才需要執行。


如果不支援BLE,你應該優雅的禁止一些使用BLE的功能。如果支援BLE,但是目前禁用了,那麼你需要在不離開你的應用程式狀態下,請求使用者啟用藍芽用能。這個過程需要使用BluetoothAdapter,分兩個步驟完成:


3.1 擷取BluetoothAdapter。


基本上所有使用藍芽的activity都需要BluetoothAdapter。BluetoothAdapter代表了裝置本身的藍芽適配器(藍芽發送接收器)。在整個系統中有一個BluetoothAdapter對象,你的應用程式可以使用這個對象進行互動。下面的程式碼片段展示了如果擷取這個適配器。注意下面的這種方法使用getSystemService()方法來擷取一個BluetoothManager執行個體,之後再通過BluetoothManager擷取BluetoothAdapter。Android 4.3(API Level 18)才開始支援BluetoothManager:

// 初始化藍芽適配器.final BluetoothManager bluetoothManager =        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);mBluetoothAdapter = bluetoothManager.getAdapter();

3.2 啟用藍芽

下一步,你需要確保藍芽已經啟動。調用isEnable()方法來檢查藍芽當前是否已經啟用。如果方法返回false,說明藍芽被禁用了。下面的程式碼片段中檢查藍芽是否已經啟用。如果沒有啟用,程式碼片段會顯示一個錯誤提示使用者去設定中啟用藍芽:

private BluetoothAdapter mBluetoothAdapter;...// 確認裝置支援藍芽並且已經啟用. 如果沒有,// 顯示一個對話方塊要求使用者授權啟用藍芽.if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);}

4、Finding BLE Devices(搜尋BLE裝置)

搜尋BLE裝置,你可以使用startLeScan()方法。這個方法需要一個BluetoothAdapter.LeScanCallback對象作為參數。你必須實現這個callback介面,因為掃描的結果會通過這個介面返回。由於搜尋裝置是比較耗電的操作,你應該遵循以下指南使用:


一旦你找到目標裝置,應該馬上停止搜尋。

不要死迴圈搜尋,並設定搜尋的最長時間。一台以前可以訪問的裝置可能已經移出了可檢測範圍,繼續掃描只會消耗電量。


下面的程式碼片段展示了如何開始和停止搜尋:

/** * 掃描和顯示可訪問BLE裝置的Activity. */public class DeviceScanActivity extends ListActivity {    private BluetoothAdapter mBluetoothAdapter;    private boolean mScanning;    private Handler mHandler;    // 10秒鐘後停止掃描.    private static final long SCAN_PERIOD = 10000;    ...    private void scanLeDevice(final boolean enable) {        if (enable) {            // 在預定義的掃描時間周期後停止掃描.            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)方法,並提供一個你的應用程式所支援的GATT服務的UUID對象數組。


下面是一個BluetoothAdapter.LeScanCallback的實現,它是一個用於接收BLE搜尋結果的介面:

private LeDeviceListAdapter mLeDeviceListAdapter;...// 裝置搜尋回調介面.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();           }       });   }};

注意:正如Bluetooth文檔中所描述的,在同一個時間你只能搜尋BLE裝置或者搜尋傳統藍牙裝置。你不能同時搜尋BLE裝置和傳統藍牙裝置。


5、Connecting to a GATT Server(串連一個GATT服務)

與BLE裝置互動的第一步就是要串連上它——更準確的說,是串連裝置上的GATT服務。串連BLE裝置上的GATT服務,你可以使用connectGatt()方法。這個方法需要三個參數:一個Context對象,autoConnect(一個表示是否當BLE裝置可訪問時馬上自動連接的boolean值),還有一個BluetoothGattCallbackduixiang:

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

上面的代碼會串連BLE裝置管理的GATT服務,並返回一個BluetoothGatt執行個體,通過這個執行個體就可以執行GATT用戶端的相關操作。這個調用者(Android應用程式)就是GATT用戶端。裡面的BluetoothGattCallback對象用於交付操作結果給用戶端,例如串連狀態,還有將來一些GATT用戶端操作的結果。


在這個例子中,BLE應用程式提供了一個activity(DeviceControlActivity)來串連、顯示資料,和顯示BLE裝置所支援的GATT的service以及characteristic。基於使用者的輸入,這個activity會和一個名為BluetoothLeService的Service通訊,這個service通過Android BLE的API與BLE裝置進行互動。

// 一個通過Android BLE API與BLE裝置進行互動的service.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);    // 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, "串連GATT服務.");                Log.i(TAG, "嘗試開始service搜尋:" +                        mBluetoothGatt.discoverServices());            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {                intentAction = ACTION_GATT_DISCONNECTED;                mConnectionState = STATE_DISCONNECTED;                Log.i(TAG, "斷開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()協助方法並傳遞一個操作標識。注意本節中的資料是根據藍芽心率測量的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);    // 按照心率測量的profile進行的特定處理.    // 按照麼一個profile規範進行資料解析.    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 {        // 針對其他profiles, 將資料格式化為16禁止資料.        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,下面的事件通過一個BroadcaseReceiver處理:

// 處理Service發送過來的各種時間.// ACTION_GATT_CONNECTED: 串連上了一個GATT服務.// ACTION_GATT_DISCONNECTED: 斷開了一個GATT服務.// ACTION_GATT_SERVICES_DISCOVERED: 發現了GATT服務.// ACTION_DATA_AVAILABLE: 從裝置接收到資料. 這裡可能是一個讀取或者通知操作的結果。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)) {            // 顯示所有支援的service和characteristic。            displayGattServices(mBluetoothLeService.getSupportedGattServices());        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));        }    }};

6、Reading BLE Attribute(讀取BLE屬性)

一旦你的Android應用程式串連上了一個GATT服務並且發現了裝置上的service,就可以在支援讀寫的地方讀寫屬性。例如,下面的程式碼片段通過迭代服務的service和characteristic,並將它們顯示在介面上:

public class DeviceControlActivity extends Activity {    ...    // 示範如何迭代所支援的GATT Services/Characteristics.    // 在這個例子中,我們填充綁定到ExpandableListView的資料結構。    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>>();        // 迴圈迭代可訪問的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>();           // 迴圈迭代可訪問的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);         }    ...    }...}


7、Receiving GATT Notification(接收GATT通知)

BLE應用程式要求在裝置的某個指定characteristic改變的時候接收到通知是很常見。下面的程式碼片段展示了如何通過使用setCharacteristicNotification()為一個characteristic設定通知:

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);

一旦為一個characteristic啟用了通知,當遠程裝置上的characteristic改變的時候就會觸發onCharacteristicChanged()方法:

@Override// Characteristic notificationpublic void onCharacteristicChanged(BluetoothGatt gatt,        BluetoothGattCharacteristic characteristic) {    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);}

8、Closing the Client App(關閉用戶端應用程式)

一旦你的應用程式使用完BLE裝置,你應該調用close()方法,這樣系統才能適當釋放佔用的資源:

public void close() {    if (mBluetoothGatt == null) {        return;    }    mBluetoothGatt.close();    mBluetoothGatt = null;}


原文地址:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html



Android Bluetooth Low Energy(Android低功耗藍芽)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.