日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

android蓝牙4.0使用方法

發布時間:2023/12/10 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android蓝牙4.0使用方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

藍牙介紹

????Android?4.3(API?Level?18)介紹了內置平臺支持藍牙低能量的核心作用,并提供了API,應用程序可以用它來發現設備,查詢服務,和讀寫字符。與傳統的藍牙相比,Bluetooth?Low?Energy?(BLE)?旨在提供顯著降低功耗。這使得Android應用能夠與具有BLE的低耗能設備進行通信,例如,傳感器、心率監視器,健身設備,等等。

BLE?權限

????為了在應用程序中使用藍牙功能,必須聲明藍牙藍牙許可。您需要這個權限執行任何藍牙通信,如請求連接,接受連接,傳輸數據。?

????聲明藍牙權限需要在應用的manifest?文件中加如下代碼:

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

?

如果你想聲明應用程序僅BLE-capable設備可用,在你的應用程序的清單包括以下:?

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

然而,如果你想讓你的應用程序可用的設備不支持BLE,你應該還是這個元素包含在您的應用程序的清單,但在運行時設置android:required=“false”。在運行時您可以決定BLE可用性通過使用PackageManager.hasSystemFeature():?

????????? //用這個檢查設備是否支持BLE。
???????? if?(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))?{
???????????????????? Toast.makeText(this,?R.string.ble_not_supported,?Toast.LENGTH_SHORT).show();
????????????????? ??finish();
??????????????? }

設置BLE

????BLE在您的應用程序可以交互之前,你需要確認在設備上是支持BLE,如果是這樣,確保啟用。注意這檢查需要設置<?uses-feature…/?>為false

????如果不支持BLE,那么你應該禁用任何BLE特性。如果支持,但是已經禁用,你可以用你的應用啟動它。完成這個設置需要兩步,使用BluetoothAdapter

1.獲取luetoothAdapter。

????BluetoothAdapter代表設備的藍牙適配器。整個系統有一個藍牙適配器,和您的應用程序可以使用這個對象與它交互。下面的代碼片段顯示了如何獲取適配器。使用getSystemService?()返回一個BluetoothManager實例,然后獲取適配器。

Android?4.3(API?LEVEL?18)引入了BluetoothManager:

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

2.啟動藍牙

???接下來,您需要確保啟用藍牙。用isEnabled()檢查藍牙當前是否啟動。如果這個方法返回false,那么藍牙是關閉的。下面的代碼片段檢查是否啟用藍牙。如果沒有,將提示用戶去設置啟用藍牙。


if?(mBluetoothAdapter?==?null?||?!mBluetoothAdapter.isEnabled())?{
????Intent?enableBtIntent?=?new?Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
????startActivityForResult(enableBtIntent,?REQUEST_ENABLE_BT);
}

?

搜索藍牙設備

??搜索藍牙設備使用startLeScan()方法。該方法以BluetoothAdapter.LeScanCallback作為參數,您必須實現這個回調,因為這是如何返回掃描結果。因為掃描非常耗電,你應該遵守如下規則:

·?只要找到了設備就應該停止搜索。

·?不要在一個無限循環中搜索,?需要設置一個時間限制搜索.?

?

下面代碼作用是如何開始和結束搜索:

?

?


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對象數組,指定藍牙服務應用程序所支持的。?

????這里使用BluetoothAdapter.LeScanCallback的實現用來顯示藍牙掃描結果:

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服務器。連接到GATT服務器使用connectGatt()方法,這個方法取三個參數:一個上下文對象,(布爾指示是否自動連接到設備就可用),和BluetoothGattCallback回調函數。

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

????這個連接到GATT服務端通過BLE設備,并返回一個BluetoothGatt實例,然后您可以使用GATT客戶端進行操作。調用者(Android應用程序)是GATT客戶端。BluetoothGattCallback用于提供結果給客戶端,如連接狀態,以及任何進一步的GATT客戶端操作。

?????在這個例子中,有幸獲得應用程序提供了一個活動(DeviceControlActivity)連接,顯示數據,并顯示GATT服務和支持的設備特征。基于用戶輸入,此活動與一個服務交互稱為BluetoothLeService,服務與BLE設備交互是通過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()輔助方法并將其傳遞一個action。注意,本節中的數據解析執行按照藍牙心率測量概要文件規范:

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

Back?in?DeviceControlActivity,?these?events?are?handled?by?a?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屬性?

????一旦你的Android應用程序連接到一個GATT服務器和發現服務,它可以讀取和寫入屬性。例如,這段代碼遍歷服務器的服務和數據并將它們顯示在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的應用通知。這個代碼片段顯示了如何設置一個通知特性,使用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);

?????一旦通知作為一個特性被啟用,如果遠程設備上的特性變化將觸發onCharacteristicChanged()回調

?

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

關閉客戶端應用

?

????一旦應用程序完成使用BLE設備,應該調用close()方法去釋放系統資源。

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

總結

以上是生活随笔為你收集整理的android蓝牙4.0使用方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。