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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android蓝牙开发与串口蓝牙通讯

發布時間:2023/12/16 Android 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android蓝牙开发与串口蓝牙通讯 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Android APP實現與串口藍牙模塊通訊,單次接收20bytes,發送10bytes

Android開發平臺示例:BluetoothLeGatt

https://github.com/android/connectivity-samples/tree/main/BluetoothLeGatt/

1、設備是否支持藍牙

?//獲取藍牙適配器BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (mBluetoothAdapter == null) {// 說明此設備不支持藍牙操作Log.d(TAG, "onCreate: 設備不支持藍牙操作");Toast.makeText(this, "設備不支持藍牙", Toast.LENGTH_SHORT).show();//如果應用必須有藍牙,則退出應用finish();}

2、設備是否開啟藍牙,未開啟則開啟藍牙

// 檢測藍牙是否開啟,開啟藍牙if (!mBluetoothAdapter.isEnabled()) {//未開啟//開啟藍牙Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(enableBtIntent, REQUEST_ENBLE_BT);//系統會彈出是否同意打開窗口,用戶點擊后會回調onActivityResult}?@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == REQUEST_ENBLE_BT) {if (resultCode == RESULT_OK) {Toast.makeText(this, "點擊了OK,藍牙已經開啟", Toast.LENGTH_SHORT).show();} else if (resultCode == RESULT_CANCELED) {Toast.makeText(this, "點擊了取消,藍牙沒開啟", Toast.LENGTH_SHORT).show();//如果應用必須開啟藍牙,則退出應用finish();}}}

3、權限申請

AndroidManifest.xml 里面聲明權限:<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /><uses-feature android:name="android.hardware.location.gps" /><!-- 打開位置權限。如果應用沒有位置權限,藍牙掃描功能不能使用,需要動態申請(Build.VERSION.SDK_INT < 23 不需要) --><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

4、查詢手機已配對的設備

//通過 getBondedDevices() 來實現,這將返回表示已配對設備的一組 BluetoothDevice 。Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();if (pairedDevices.size() > 0) {for (BluetoothDevice device : pairedDevices) {Log.d(TAG, device.getName() + " " + device.getAddress());}}

5、創建掃描器

if (mBluetoothAdapter != null) {BluetoothLeScanner mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); //獲取掃描器BluetoothLeScanner mSampleScanCallback = new SampleScanCallback(); //創建掃描回調//注意:掃描回調只能創建一次,關閉掃描的時候也要使用同一回調,不然不能停止 }private class SampleScanCallback extends ScanCallback {@Overridepublic void onScanResult(int callbackType, ScanResult result) {} //得到掃描的設備@Overridepublic void onBatchScanResults(List<ScanResult> results) {}@Overridepublic void onScanFailed(int errorCode) {} }

6、開始掃描

?//藍牙設備開始掃描 注意:掃描只能開啟一次,不然不能停止。(可能是開幾次就要關幾次,沒有驗證)private void bluetoothStartScanDevices() {if (mBluetoothLeScanner != null) {mBluetoothLeScanner.startScan(mSampleScanCallback);}}

7、停止掃描

private void bluetoothStopScanDevices() {// 通過調用 BluetoothLeScanner.stopScan 可以停止正在進行的藍牙掃描。// 這里需要注意的是,傳入的回調必須是開啟藍牙掃描時傳入的回調,否則藍牙掃描不會停止。if (mBluetoothLeScanner != null) {mBluetoothLeScanner.stopScan(mSampleScanCallback);}}

8、創建服務類BluetootheService,用服務來管理藍牙的連接與通訊

public class BluetoothLeService extends Service {private final IBinder mBinder = new LocalBinder();public class LocalBinder extends Binder {public BluetoothLeService getService() {return BluetoothLeService.this;}}@Overridepublic IBinder onBind(Intent intent) {return mBinder;}?@Overridepublic boolean onUnbind(Intent intent) {close();return super.onUnbind(intent);}}

9、聲明服務

AndroidManifest.xml 里面聲明服務: <application<service android:name=".BluetoothManage.BluetoothLeService" android:enabled="true"/>

10、綁定服務,在Activity里綁定,此Activity將收到服務的通知,并進行數據交互

Intent gattServiceIntent = new Intent(DevicesSearchActivity.this, BluetoothLeService.class); boolean isOK = bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE); //綁定失敗檢查AndroidManifest是否有聲明private final ServiceConnection mServiceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) { //與服務連接完成mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();mBluetoothLeService.connect(mDeviceAddress);}@Overridepublic void onServiceDisconnected(ComponentName name) { //與服務斷開連接mBluetoothLeService = null;} };

11、在Activity里注冊廣播接收器,接收服務發出的廣播,后面有里面的詳細處理

private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {} }

12、在服務類BluetootheService里創建連接

public boolean connect(final String address) {if (mBluetoothAdapter == null || address == null) { return false;}if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {if (mBluetoothGatt.connect()) { mConnectionState = STATE_CONNECTING; return true; } else { return false;}}final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);if (device == null) { return false; }mBluetoothGatt = device.connectGatt(this, true, mGattCallback);return true; }

13、連接回調

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { //連接狀態改變調用String intentAction;if (newState == BluetoothProfile.STATE_CONNECTED) { //連接完成broadcastUpdate(ACTION_GATT_CONNECTED); //連接完成廣播} else if (newState == BluetoothProfile.STATE_DISCONNECTED) { //連接斷開broadcastUpdate(ACTION_GATT_DISCONNECTED); //連接斷開廣播}}@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {if (status == BluetoothGatt.GATT_SUCCESS) { //連接完成后發現服務broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED); //發現服務廣播}}@Overridepublic void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); //收到數據廣播}}@Overridepublic void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); //收到數據廣播} };

14、在Activity里廣播接收器的詳細處理

private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {final String action = intent.getAction();if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { // 連接成功mConnectionState = STATE_CONNECTED;invalidateOptionsMenu();} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { // 斷開連接mConnectionState = STATE_DISCONNECTED;invalidateOptionsMenu();} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) { // 發現有可支持的服務//獲取GATT服務 + UUIDmBluetoothGattService = mBluetoothLeService.getSupportedGattServices(UUID.fromString(SampleGattAttributes.UUID_SERVICE));//根據GATT服務獲取寫數據端口 + UUIDmWriteBluetoothGattCharacteristic = mBluetoothGattService.getCharacteristic(UUID.fromString(SampleGattAttributes.UUID_WRITE));//根據GATT服務獲取讀數據端口 + UUIDmReadBluetoothGattCharacteristic = mBluetoothGattService.getCharacteristic(UUID.fromString(SampleGattAttributes.UUID_NOTIFY));//打開讀取數據通道mBluetoothLeService.setCharacteristicNotification(mReadBluetoothGattCharacteristic, true);Log.d(TAG, "onReceive: 發現有可支持的服務");} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { //收到數據String dataStr = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);Log.d(TAG, "onReceive: Data" + dataStr);writeDataToBluetooth(); //發送數據}} };

15、發送數據,在Activity里

public void writeDataToBluetooth() {byte[] WriteBytes = new byte[10];mWriteBluetoothGattCharacteristic.setValue(WriteBytes);mWriteBluetoothGattCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);mBluetoothLeService.writeCharacteristic(mWriteBluetoothGattCharacteristic); }

16、讀取RSSI,在BluetoothLeService服務類里

mBluetoothGatt.readRemoteRssi();//readRemoteRssi讀取信號強度函數調用后,在BluetoothGattCallback里回調 @Override public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {super.onReadRemoteRssi(gatt, rssi, status);Log.d(TAG, "onReadRemoteRssi: " + rssi);broadcastUpdateRSSI(ACTION_RSSI_VALUE, String.valueOf(rssi)); //廣播發送給activity }

總結

以上是生活随笔為你收集整理的Android蓝牙开发与串口蓝牙通讯的全部內容,希望文章能夠幫你解決所遇到的問題。

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