安卓低功耗藍芽——手機作為外圍裝置

來源:互聯網
上載者:User

標籤:context   asm   eset   des   out   res   number   資源   level   

概述

自安卓5.0後,Google加入了對安卓手機作為低功耗藍芽外圍裝置,即服務端的支援。使得手機可以通過低功耗藍芽進行相互連信。

開發步驟

實現這一功能其實只需要分為設定廣播和設定伺服器兩個部分完成即可

設定伺服器

這一步驟主要操作的是BluetoothGattServer。 

1. 定義一個BluetoothGattServerCallback的回調如下

private BluetoothGattServerCallback bluetoothGattServerCallback = new BluetoothGattServerCallback() {        @Override        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {            Log.v("onConnectionStateChange","串連狀態改變");        }        @Override        public void onServiceAdded(int status, BluetoothGattService service) {            Log.v("onServiceAdded","成功添加服務");        }        @Override        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {            Log.v("CharacteristicReadReq","遠程裝置請求讀取資料");            bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, new byte[]{1,2,3,4,5,6,7,8,9,0});        }        @Override        public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {            Log.v("CharacteristicWriteReq","遠程裝置請求寫入資料");            bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, new byte[]{0,9,8,7,6,5,4,3,2,1});        @Override        public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {            Log.v("DescriptorReadReq","遠程裝置請求寫入描述器");            bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, new byte[]{10,11,12,13,14,15,16,17,18,19});        }        @Override        public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {            Log.v("DescriptorReadReq","遠程裝置請求寫入描述器");            bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, new byte[]{19,18,17,16,15,14,13,12,11,10});        }        @Override        public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {            Log.v("onExecuteWrite","執行掛起寫入操作");        }        @Override        public void onNotificationSent(BluetoothDevice device, int status) {            Log.v("onNotificationSent","通知發送");        }        @Override        public void onMtuChanged(BluetoothDevice device, int mtu) {            Log.v("onMtuChanged","mtu改變");        }    };
  1. 利用BluetoothManager的openGattServer(Context,BluetoothServerCallback)方法獲得BluetoothGattServer執行個體。
BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);bluetoothGattServer = mBluetoothManager.openGattServer(this, bluetoothGattServerCallback);

3.為裝置添加相應的service,characteristic和descriptor(非必須,但通常都會用到)。這裡僅舉一個例子。

BluetoothGattCharacteristic characteristic= new BluetoothGattCharacteristic(CHARACTERISTIC_UUID,por,per);        BluetoothGattService service= new BluetoothGattService(SERVICE_UUID,pri);        service.addCharacteristic(characteristic);        bluetoothGattServer.addService(service);

其中,por,per,pri分別為:

private int por = BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_INDICATE | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE;    private int per = BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE;    private int pri = BluetoothGattService.SERVICE_TYPE_PRIMARY;

可根據自己的需要進行調整。 
這樣就完成了對BluetoothGattServer的簡單設定。

設定廣播

這裡主要操作BluetoothLeAdvertiser。 

1. 利用BluetoothManager擷取BluetoothAdapter,然後再通過BluetoothAdapter的getBluetoothLeAdvertiser()方法擷取BluetoothLeAdvertiser的執行個體。

BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);        mBluetoothAdapter = mBluetoothManager.getAdapter();        mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
  1. 開啟廣播 

    這裡需要準備三個東西,AdvertiseSettings,AdvertiseData和AdvertiseCallback。 
    • AdvertiseSettings 
      廣播的配置執行個體,通過AdvertiseSettings.Builder獲得。 

      AdvertiseSettings.Builder具有四個設定參數的方法。 
      分別是
setAdvertiseMode(int advertiseMode)設定廣播的模式,低功耗,平衡和低延遲三種模式;setConnectable(boolean connectable)設定是否可以串連。setTimeout(int timeoutMillis)設定廣播的最長時間setTxPowerLevel(int txPowerLevel)設定廣播的訊號強度

可根據需要自行設定,若不設定則按照預設的參數設定。 
這裡只提供一個小例子。

AdvertiseSettings settings = new AdvertiseSettings.Builder()                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)                .setTimeout(0)                .setConnectable(true)                .build();
  • AdvertiseData 
    廣播內容的執行個體,通過AdvertiseData.Builder獲得 

    內含幾個成員函數。
addManufacturerData(int manufacturerId, byte[] manufacturerSpecificData)添加廠商資訊,貌似不怎麼用到。addServiceUuid(ParcelUuid serviceUuid),addServiceData(ParcelUuid serviceDataUuid, byte[] serviceData)添加服務進廣播,即對外廣播本裝置擁有的服務。setIncludeDeviceName(boolean includeDeviceName)是否廣播裝置名稱。setIncludeTxPowerLevel(boolean includeTxPowerLevel)是否廣播訊號強度

這裡提供一個簡單的例子。

AdvertiseData advertiseData = new AdvertiseData.Builder()                .setIncludeDeviceName(true)                .setIncludeTxPowerLevel(true)                .addServiceUuid(new ParcelUuid(SERVICE_UUID))                .build();
  • AdvertiseCallback 
    廣播成功或者失敗的回調,比較簡單。
private AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() {        @Override        public void onStartSuccess(AdvertiseSettings settingsInEffect) {            Log.v("start","廣播成功");        }        @Override        public void onStartFailure(int errorCode) {            Log.v("廣播失敗",String.valueOf(errorCode));        }    };

最後通過BluetoothLeAdvertise的startAdvertising(AdvertiseSettings settings, AdvertiseData advertiseData, AdvertiseCallback callback)開啟廣播即可 
3. 關閉廣播 
通過BluetoothLeAdvertise的stopAdvertising(AdvertiseCallback callback)關閉。

參考連結:https://developer.android.google.cn/reference/android/bluetooth/le/BluetoothLeAdvertiser.html 
代碼資源:http://download.csdn.net/detail/will4906/9777135

安卓低功耗藍芽——手機作為外圍裝置

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.