当前位置:   article > 正文

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

android蓝牙串口通信

Android APP实现与串口蓝牙模块通讯,单次接收20bytes,发送10bytes

Android开发平台示例:BluetoothLeGatt

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

1、设备是否支持蓝牙

  1.  //获取蓝牙适配器
  2.  BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  3.  if (mBluetoothAdapter == null) {
  4.      // 说明此设备不支持蓝牙操作
  5.      Log.d(TAG, "onCreate: 设备不支持蓝牙操作");
  6.      Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
  7.      //如果应用必须有蓝牙,则退出应用
  8.      finish();
  9.  }

2、设备是否开启蓝牙,未开启则开启蓝牙

  1. // 检测蓝牙是否开启,开启蓝牙
  2.  if (!mBluetoothAdapter.isEnabled()) {
  3.      //未开启
  4.      //开启蓝牙
  5.      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  6.      startActivityForResult(enableBtIntent, REQUEST_ENBLE_BT);
  7.      //系统会弹出是否同意打开窗口,用户点击后会回调onActivityResult
  8.  }
  9.  ​
  10.  @Override
  11.  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  12.      super.onActivityResult(requestCode, resultCode, data);
  13.      if (requestCode == REQUEST_ENBLE_BT) {
  14.          if (resultCode == RESULT_OK) {
  15.              Toast.makeText(this, "点击了OK,蓝牙已经开启", Toast.LENGTH_SHORT).show();
  16.         } else if (resultCode == RESULT_CANCELED) {
  17.              Toast.makeText(this, "点击了取消,蓝牙没开启", Toast.LENGTH_SHORT).show();
  18.              //如果应用必须开启蓝牙,则退出应用
  19.              finish();
  20.         }
  21.     }
  22.  }

3、权限申请

  1. AndroidManifest.xml 里面声明权限:
  2.      
  3.  <uses-permission android:name="android.permission.BLUETOOTH" />
  4.  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  5.  <uses-feature android:name="android.hardware.location.gps" />
  6.      
  7.  <!-- 打开位置权限。如果应用没有位置权限,蓝牙扫描功能不能使用,需要动态申请(Build.VERSION.SDK_INT < 23 不需要) -->
  8.  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  9.  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

4、查询手机已配对的设备

  1. //通过 getBondedDevices() 来实现,这将返回表示已配对设备的一组 BluetoothDevice 。
  2.  Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
  3.  if (pairedDevices.size() > 0) {
  4.      for (BluetoothDevice device : pairedDevices) {
  5.          Log.d(TAG, device.getName() + " " + device.getAddress());
  6.     }
  7.  }

5、创建扫描器

  1. if (mBluetoothAdapter != null) {
  2. BluetoothLeScanner mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); //获取扫描器
  3. BluetoothLeScanner mSampleScanCallback = new SampleScanCallback(); //创建扫描回调
  4. //注意:扫描回调只能创建一次,关闭扫描的时候也要使用同一回调,不然不能停止
  5. }
  6. private class SampleScanCallback extends ScanCallback {
  7. @Override
  8. public void onScanResult(int callbackType, ScanResult result) {} //得到扫描的设备
  9. @Override
  10. public void onBatchScanResults(List<ScanResult> results) {}
  11. @Override
  12. public void onScanFailed(int errorCode) {}
  13. }

6、开始扫描

  1.  //蓝牙设备开始扫描 注意:扫描只能开启一次,不然不能停止。(可能是开几次就要关几次,没有验证)
  2.  private void bluetoothStartScanDevices() {
  3.      if (mBluetoothLeScanner != null) {
  4.          mBluetoothLeScanner.startScan(mSampleScanCallback);
  5.     }
  6.  }

7、停止扫描

  1. private void bluetoothStopScanDevices() {
  2.       // 通过调用 BluetoothLeScanner.stopScan 可以停止正在进行的蓝牙扫描。
  3.       // 这里需要注意的是,传入的回调必须是开启蓝牙扫描时传入的回调,否则蓝牙扫描不会停止。
  4.      if (mBluetoothLeScanner != null) {
  5.          mBluetoothLeScanner.stopScan(mSampleScanCallback);
  6.     }
  7.  }

8、创建服务类BluetootheService,用服务来管理蓝牙的连接与通讯

  1. public class BluetoothLeService extends Service {
  2.      private final IBinder mBinder = new LocalBinder();
  3.      
  4.      public class LocalBinder extends Binder {
  5.          public BluetoothLeService getService() {
  6.              return BluetoothLeService.this;
  7.         }
  8.     }
  9.      
  10.      @Override
  11.      public IBinder onBind(Intent intent) {
  12.          return mBinder;
  13.     }
  14.  ​
  15.      @Override
  16.      public boolean onUnbind(Intent intent) {
  17.          close();
  18.          return super.onUnbind(intent);
  19.     }
  20.  }

9、声明服务

  1. AndroidManifest.xml 里面声明服务:
  2. <application
  3. <service android:name=".BluetoothManage.BluetoothLeService" android:enabled="true"/>

10、绑定服务,在Activity里绑定,此Activity将收到服务的通知,并进行数据交互

  1. Intent gattServiceIntent = new Intent(DevicesSearchActivity.this, BluetoothLeService.class);
  2. boolean isOK = bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE); //绑定失败检查AndroidManifest是否有声明
  3. private final ServiceConnection mServiceConnection = new ServiceConnection() {
  4. @Override
  5. public void onServiceConnected(ComponentName name, IBinder service) { //与服务连接完成
  6. mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
  7. mBluetoothLeService.connect(mDeviceAddress);
  8. }
  9. @Override
  10. public void onServiceDisconnected(ComponentName name) { //与服务断开连接
  11. mBluetoothLeService = null;
  12. }
  13. };

11、在Activity里注册广播接收器,接收服务发出的广播,后面有里面的详细处理

  1. private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
  2. @Override
  3. public void onReceive(Context context, Intent intent) {}
  4. }

12、在服务类BluetootheService里创建连接

  1. public boolean connect(final String address) {
  2. if (mBluetoothAdapter == null || address == null) { return false;}
  3. if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
  4. if (mBluetoothGatt.connect()) { mConnectionState = STATE_CONNECTING; return true; } else { return false;}
  5. }
  6. final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  7. if (device == null) { return false; }
  8. mBluetoothGatt = device.connectGatt(this, true, mGattCallback);
  9. return true;
  10. }

13、连接回调

  1. private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
  2. @Override
  3. public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { //连接状态改变调用
  4. String intentAction;
  5. if (newState == BluetoothProfile.STATE_CONNECTED) { //连接完成
  6. broadcastUpdate(ACTION_GATT_CONNECTED); //连接完成广播
  7. } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { //连接断开
  8. broadcastUpdate(ACTION_GATT_DISCONNECTED); //连接断开广播
  9. }
  10. }
  11. @Override
  12. public void onServicesDiscovered(BluetoothGatt gatt, int status) {
  13. if (status == BluetoothGatt.GATT_SUCCESS) { //连接完成后发现服务
  14. broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED); //发现服务广播
  15. }
  16. }
  17. @Override
  18. public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
  19. if (status == BluetoothGatt.GATT_SUCCESS) {
  20. broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); //收到数据广播
  21. }
  22. }
  23. @Override
  24. public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
  25. broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); //收到数据广播
  26. }
  27. };

14、在Activity里广播接收器的详细处理

  1. private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
  2. @Override
  3. public void onReceive(Context context, Intent intent) {
  4. final String action = intent.getAction();
  5. if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { // 连接成功
  6. mConnectionState = STATE_CONNECTED;
  7. invalidateOptionsMenu();
  8. } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { // 断开连接
  9. mConnectionState = STATE_DISCONNECTED;
  10. invalidateOptionsMenu();
  11. } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) { // 发现有可支持的服务//获取GATT服务 + UUID
  12. mBluetoothGattService = mBluetoothLeService.getSupportedGattServices(UUID.fromString(SampleGattAttributes.UUID_SERVICE));
  13. //根据GATT服务获取写数据端口 + UUID
  14. mWriteBluetoothGattCharacteristic = mBluetoothGattService.getCharacteristic(UUID.fromString(SampleGattAttributes.UUID_WRITE));
  15. //根据GATT服务获取读数据端口 + UUID
  16. mReadBluetoothGattCharacteristic = mBluetoothGattService.getCharacteristic(UUID.fromString(SampleGattAttributes.UUID_NOTIFY));
  17. //打开读取数据通道
  18. mBluetoothLeService.setCharacteristicNotification(mReadBluetoothGattCharacteristic, true);
  19. Log.d(TAG, "onReceive: 发现有可支持的服务");
  20. } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { //收到数据
  21. String dataStr = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
  22. Log.d(TAG, "onReceive: Data" + dataStr);
  23. writeDataToBluetooth(); //发送数据
  24. }
  25. }
  26. };

15、发送数据,在Activity

  1. public void writeDataToBluetooth() {
  2. byte[] WriteBytes = new byte[10];
  3. mWriteBluetoothGattCharacteristic.setValue(WriteBytes);
  4. mWriteBluetoothGattCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
  5. mBluetoothLeService.writeCharacteristic(mWriteBluetoothGattCharacteristic);
  6. }

16、读取RSSI,在BluetoothLeService服务类里

  1. mBluetoothGatt.readRemoteRssi();
  2. //readRemoteRssi读取信号强度函数调用后,在BluetoothGattCallback里回调
  3. @Override
  4. public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
  5. super.onReadRemoteRssi(gatt, rssi, status);
  6. Log.d(TAG, "onReadRemoteRssi: " + rssi);
  7. broadcastUpdateRSSI(ACTION_RSSI_VALUE, String.valueOf(rssi)); //广播发送给activity
  8. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/225336?site
推荐阅读
相关标签
  

闽ICP备14008679号