当前位置:   article > 正文

Android BlueToothBLE入门(二)——设备的连接和通讯(附Demo源码地址)_android studio kotlin ble蓝牙连接

android studio kotlin ble蓝牙连接

学更好的别人,

做更好的自己。

——《微卡智享》

f98a7c1995354157b92adeec3f3f0d95.jpeg

本文长度为7870,预计阅读12分钟

前言

接《Android BlueToothBLE入门(一)——低功耗蓝牙介绍》上篇,这篇文章主要就是来做Demo实现Android两台设备的数据通讯。

265be150c55a258e1f6706ac4b187866.png

实现效果

a9419e281e36da4547eac0c7a83bfeab.jpeg

Android BLE Demo简介

256e157d1778e648caefe10bac58b2a3.png

微卡智享

01

目录及使用的组件

5b702abca0dd6934c392134519936e8c.png

整个Demo的目录上图中已经做了说明,其中最核心的是BlueToothBLEUtil类,这是把这个Demo中用到的BLE蓝牙方法都放到这里了,因为中心设备(Client)和外围设备(Server)统一用的这个程序,所以这个类里面中心设备和外围设备用到的都做了一个封装,当时还有不少要加的,后面会再补充。

Demo使用的MVI架构(Jeppack Compose还不会,所以用的viewBinding),像RecyclerView的适配器这块还是使用的BaseQuickAdapter,现在4.0在测试过程中了,所以我直接用的4.0beta版,蓝牙权限的申请采用了easypermissions,确实比自己写方便了许多。

build.gradle相关依赖项

09dcaad06b31cb7f24cc55c73f24c631.png

  1. dependencies {
  2.     'androidx.lifecycle:lifecycle-livedata-ktx:2.4.1'
  3.     'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1'
  4.     'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
  5. //使用协程
  6.     "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4"
  7.     "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"
  8.     "io.github.cymchad:BaseRecyclerViewAdapterHelper:4.0.0-beta04"
  9. // 使用 Android X 的应用添加该依赖
  10.     'pub.devrel:easypermissions:3.0.0'
  11. }

02

蓝牙核心类BlueToothBLEUtil

外围设备和中心设备通讯,我们就用自己定义的服务即可,所以类中我们已经定义好常量来实现。

上一篇介绍过蓝牙技术联盟SIG定义UUID共用了一个基本的UUID:0x0000xxxx-0000-1000-8000-00805F9B34FB。总共128位,为了进一步简化基本UUID,每一个蓝牙技术联盟定义的属性有一个唯一的16位UUID,以代替上面的基本UUID的‘x’部分。使用16位的UUID便于记忆和操作。

所以类中我们定义的服务UUID只是中间xxxx四位即可,写了一个函数来直接生成对应的UUID

5bbfc6913293fc3e1a4747e010ab39b5.png

1489f97e1ade6e92d179a7221d9734e5.png

代码中使用BLE蓝牙相关Api时,Android Studio会经常提示要先判断是否有蓝牙权限,所以这里也是把蓝牙是否做过初始化,和判断是否有相关的蓝牙权限写了一个函数调用

1d1ee7d358d67e675fcc1edbe7d1e755.png

蓝牙权限

9befaca7fc6d9872dbdac39d75a078d2.png

检测是否有相关权限

231d91049d1188143156cd4a89b930cc.png

调用蓝牙API时先检测是否有对应的权限

像扫描设备,连接设备时需要知道返回的结果,用到了回调,那类中直接就是传入相磁的CallBack回调函数,在UI界面写回调函数即可。如下面这个扫描蓝牙设备函数

f61a3c4d0586d22469834111bb540efb.png

参数为ScanCallback

3c54c36d841f4df2168248b6466b4924.png

ScanFragment中定义ScanCallback,实现onScanResult中发送意图

5c532a8aa4f6ef4c26470a42a0757f13.png

点击扫描设备直接调用类中函数并传入回调函数

BlueToothBLEUtil源码

  1. package vac.test.bluetoothbledemo.repository
  2. import android.Manifest
  3. import android.app.Application
  4. import android.bluetooth.BluetoothAdapter
  5. import android.bluetooth.BluetoothDevice
  6. import android.bluetooth.BluetoothGatt
  7. import android.bluetooth.BluetoothGattCallback
  8. import android.bluetooth.BluetoothGattCharacteristic
  9. import android.bluetooth.BluetoothGattDescriptor
  10. import android.bluetooth.BluetoothGattServer
  11. import android.bluetooth.BluetoothGattServerCallback
  12. import android.bluetooth.BluetoothGattService
  13. import android.bluetooth.BluetoothManager
  14. import android.bluetooth.le.AdvertiseCallback
  15. import android.bluetooth.le.AdvertiseData
  16. import android.bluetooth.le.AdvertiseSettings
  17. import android.bluetooth.le.BluetoothLeAdvertiser
  18. import android.bluetooth.le.ScanCallback
  19. import android.bluetooth.le.ScanFilter
  20. import android.bluetooth.le.ScanSettings
  21. import android.content.Context
  22. import android.content.pm.PackageManager
  23. import android.os.Build
  24. import android.os.ParcelUuid
  25. import android.util.Log
  26. import android.widget.Toast
  27. import androidx.core.app.ActivityCompat
  28. import kotlinx.coroutines.CoroutineScope
  29. import kotlinx.coroutines.Dispatchers
  30. import kotlinx.coroutines.delay
  31. import kotlinx.coroutines.launch
  32. import pub.devrel.easypermissions.AfterPermissionGranted
  33. import pub.devrel.easypermissions.EasyPermissions
  34. import vac.test.bluetoothbledemo.BaseApp
  35. import vac.test.bluetoothbledemo.EncodeUtil
  36. import vac.test.bluetoothbledemo.bytesToHexString
  37. import vac.test.bluetoothbledemo.ui.MainActivity
  38. import java.io.IOException
  39. import java.util.UUID
  40. object BlueToothBLEUtil {
  41. //服务 UUID
  42. const val BLESERVER = "2603"
  43. //特征 UUID
  44. const val BLECHARACTERISTIC = "ca01"
  45. //描述 UUID
  46. const val BLEDESCRIPTOR = "da01"
  47. //蓝牙相关权限
  48. const val REQUEST_CODE_PERMISSIONS = 10
  49. val REQUIRED_BLEPERMISSIONS = arrayOf(
  50. Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN,
  51. Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN,
  52. Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH_ADVERTISE
  53. )
  54. private var mBluetoothManager: BluetoothManager? = null
  55. private var mBluetoothAdapter: BluetoothAdapter? = null
  56. private var mBluetoothGattService: BluetoothGattService? = null
  57. private var mBluetoothGattServer: BluetoothGattServer? = null
  58. private var mBluetoothDevice: BluetoothDevice? = null
  59. private var mBluetoothGatt: BluetoothGatt? = null
  60. //BLE广播操作类
  61. private var mBluetoothLeAdvertiser: BluetoothLeAdvertiser? = null
  62. //是否初始化
  63. var hasInit = false
  64. lateinit var mApplication: Application
  65. //检测蓝牙权限
  66. fun checkBlueToothPermission(permissions: String = ""): Boolean {
  67. if (!hasInit) throw IOException("未初始化蓝牙BlueTooth!")
  68. if (permissions == "") return true
  69. return ActivityCompat.checkSelfPermission(
  70. mApplication.applicationContext,
  71. permissions
  72. ) == PackageManager.PERMISSION_GRANTED
  73. }
  74. fun init(application: Application): Boolean {
  75. if (hasInit) return true
  76. mApplication = application
  77. //初始化ble设配器
  78. mBluetoothManager =
  79. mApplication.applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
  80. //初始化适配器
  81. mBluetoothAdapter = mBluetoothManager!!.adapter
  82. hasInit = true
  83. return hasInit
  84. }
  85. fun destory() {
  86. mBluetoothGatt = null
  87. mBluetoothDevice = null
  88. mBluetoothGattService = null
  89. mBluetoothAdapter = null
  90. hasInit = false
  91. }
  92. //获取UUID
  93. /*
  94. 蓝牙技术联盟SIG定义UUID共用了一个基本的UUID:0x0000xxxx-0000-1000-8000-00805F9B34FB。
  95. 总共128位,为了进一步简化基本UUID,每一个蓝牙技术联盟定义的属性有一个唯一的16位UUID,
  96. 以代替上面的基本UUID的‘x’部分。使用16位的UUID便于记忆和操作
  97. */
  98. fun getUUID(baseuuid: String): UUID {
  99. return UUID.fromString("0000${baseuuid}-0000-1000-8000-00805f9b34fb")
  100. }
  101. //广播时间(设置为0则持续广播)
  102. val Time = 0
  103. //是否在扫描中
  104. private var mScanning: Boolean = false
  105. //获取BluetoothManager
  106. fun getBluetoothManager(): BluetoothManager? {
  107. return if (checkBlueToothPermission()) {
  108. mBluetoothManager
  109. } else {
  110. null
  111. }
  112. }
  113. //获取BluetoothAdapter
  114. fun getBluetoothAdapter(): BluetoothAdapter? {
  115. return if (checkBlueToothPermission()) {
  116. mBluetoothAdapter
  117. } else {
  118. null
  119. }
  120. }
  121. //region 服务端外围设备相关函数
  122. /**
  123. * 添加Gatt 服务和特征
  124. * 广播是广播,只有添加Gatt服务和特征后,连接才有服务和特征用于数据交换
  125. */
  126. //获取Gatt服务
  127. fun getGattService(): BluetoothGattService {
  128. //初始化Service
  129. //创建服务,并初始化服务的UUID和服务类型。
  130. //BluetoothGattService.SERVICE_TYPE_PRIMARY 为主要服务类型
  131. val mGattService = BluetoothGattService(
  132. getUUID(BLESERVER),
  133. BluetoothGattService.SERVICE_TYPE_PRIMARY
  134. )
  135. //初始化特征(添加读写权限)
  136. //在服务端配置特征时,设置BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE,
  137. //那么onCharacteristicWriteRequest()回调时,不需要GattServer进行response才能进行响应。
  138. val mGattCharacteristic = BluetoothGattCharacteristic(
  139. getUUID(BLECHARACTERISTIC),
  140. BluetoothGattCharacteristic.PROPERTY_WRITE or
  141. BluetoothGattCharacteristic.PROPERTY_NOTIFY or
  142. BluetoothGattCharacteristic.PROPERTY_READ,
  143. (BluetoothGattCharacteristic.PERMISSION_WRITE or BluetoothGattCharacteristic.PERMISSION_READ)
  144. )
  145. //初始化描述
  146. val mGattDescriptor = BluetoothGattDescriptor(
  147. getUUID(BLEDESCRIPTOR),
  148. BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE
  149. )
  150. //Service添加特征值
  151. mGattService.addCharacteristic(mGattCharacteristic)
  152. //特征值添加描述
  153. mGattCharacteristic.addDescriptor(mGattDescriptor)
  154. return mGattService
  155. }
  156. //添加服务
  157. fun addGattServer(mGattServerCallback: BluetoothGattServerCallback) {
  158. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  159. mBluetoothGattService = getGattService()
  160. mBluetoothGattServer =
  161. mBluetoothManager!!.openGattServer(
  162. mApplication.applicationContext, mGattServerCallback
  163. )
  164. mBluetoothGattServer!!.addService(mBluetoothGattService)
  165. }
  166. }
  167. //开启广播
  168. //官网建议获取mBluetoothLeAdvertiser时,先做mBluetoothAdapter.isMultipleAdvertisementSupported判断,
  169. // 但部分华为手机支持Ble广播却还是返回false,所以最后以mBluetoothLeAdvertiser是否不为空且蓝牙打开为准
  170. fun startAdvertising(phonename: String, mAdvertiseCallback: AdvertiseCallback): Boolean {
  171. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  172. mBluetoothAdapter!!.name = phonename
  173. mBluetoothLeAdvertiser = mBluetoothAdapter!!.bluetoothLeAdvertiser
  174. //蓝牙关闭或者不支持
  175. return if (mBluetoothLeAdvertiser != null && mBluetoothAdapter!!.isEnabled) {
  176. Log.d(
  177. "pkg", "mBluetoothLeAdvertiser != null = ${mBluetoothLeAdvertiser != null} " +
  178. "mBluetoothAdapter.isMultipleAdvertisementSupported = ${mBluetoothAdapter!!.isMultipleAdvertisementSupported}"
  179. )
  180. //开始广播(不附带扫描响应报文)
  181. mBluetoothLeAdvertiser?.startAdvertising(
  182. getAdvertiseSettings(),
  183. getAdvertiseData(), mAdvertiseCallback
  184. )
  185. true
  186. } else {
  187. false
  188. }
  189. } else {
  190. return false
  191. }
  192. }
  193. //关闭蓝牙广播
  194. fun stopAdvertising(mAdvertiseCallback: AdvertiseCallback): Boolean {
  195. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_ADVERTISE)) {
  196. mBluetoothLeAdvertiser?.let { advertiser ->
  197. advertiser.stopAdvertising(mAdvertiseCallback)
  198. }
  199. return true
  200. } else {
  201. return false
  202. }
  203. }
  204. //endregion
  205. fun scanBlueToothDevice(scancallback: ScanCallback) {
  206. if (mScanning) return
  207. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_SCAN)) {
  208. //扫描设置
  209. /**
  210. * 三种模式
  211. * - SCAN_MODE_LOW_POWER : 低功耗模式,默认此模式,如果应用不在前台,则强制此模式
  212. * - SCAN_MODE_BALANCED :平衡模式,一定频率下返回结果
  213. * - SCAN_MODE_LOW_LATENCY 高功耗模式,建议应用在前台才使用此模式
  214. */
  215. val builder = ScanSettings.Builder()
  216. .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
  217. /**
  218. * 三种回调模式
  219. * - CALLBACK_TYPE_ALL_MATCHED : 寻找符合过滤条件的广播,如果没有,则返回全部广播
  220. * - CALLBACK_TYPE_FIRST_MATCH : 仅筛选匹配第一个广播包出发结果回调的
  221. * - CALLBACK_TYPE_MATCH_LOST : 这个看英文文档吧,不满足第一个条件的时候,不好解释
  222. */
  223. builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
  224. //判断手机蓝牙芯片是否支持皮批处理扫描
  225. if (mBluetoothAdapter!!.isOffloadedFilteringSupported) {
  226. builder.setReportDelay(0L)
  227. }
  228. mScanning = true
  229. //3秒后关闭
  230. CoroutineScope(Dispatchers.IO).launch {
  231. delay(6000)
  232. stopScanBlueToothDevice(scancallback)
  233. Log.i("bluetooth", "关闭扫描")
  234. }
  235. //过滤掉不是自己程序发送的广播
  236. val filter = getScanFilter()
  237. mBluetoothAdapter!!.bluetoothLeScanner?.startScan(filter, builder.build(), scancallback)
  238. //过滤特定的 UUID 设备
  239. //bluetoothAdapter?.bluetoothLeScanner?.startScan()
  240. }
  241. }
  242. fun stopScanBlueToothDevice(scancallback: ScanCallback) {
  243. //连接时要先关闭扫描
  244. if (mScanning) {
  245. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_SCAN)) {
  246. mBluetoothAdapter!!.bluetoothLeScanner?.stopScan(scancallback)
  247. mScanning = false
  248. }
  249. }
  250. }
  251. //初始化广播设置
  252. fun getAdvertiseSettings(): AdvertiseSettings {
  253. //初始化广播设置
  254. return AdvertiseSettings.Builder()
  255. //设置广播模式,以控制广播的功率和延迟。ADVERTISE_MODE_LOW_LATENCY为高功率,低延迟
  256. .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_POWER)
  257. //设置蓝牙广播发射功率级别
  258. .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_LOW)
  259. //广播时限。最多180000毫秒。值为0将禁用时间限制。(不设置则为无限广播时长)
  260. .setTimeout(Time)
  261. //设置广告类型是可连接还是不可连接。
  262. .setConnectable(true)
  263. .build()
  264. }
  265. //设置广播报文
  266. fun getAdvertiseData(): AdvertiseData {
  267. return AdvertiseData.Builder()
  268. //设置广播包中是否包含设备名称。
  269. .setIncludeDeviceName(true)
  270. //设置广播包中是否包含发射功率
  271. .setIncludeTxPowerLevel(true)
  272. //设置UUID
  273. .addServiceUuid(ParcelUuid(getUUID(BLESERVER)))
  274. .build()
  275. }
  276. //设置扫描过滤
  277. fun getScanFilter(): ArrayList<ScanFilter> {
  278. val scanFilterList = ArrayList<ScanFilter>()
  279. val builder = ScanFilter.Builder()
  280. builder.setServiceUuid(ParcelUuid(getUUID(BLESERVER)))
  281. scanFilterList.add(builder.build())
  282. return scanFilterList
  283. }
  284. //获取原生蓝牙对象
  285. fun getBlueToothDevice(macAddress: String): BluetoothDevice? {
  286. return if (checkBlueToothPermission()) {
  287. mBluetoothDevice = mBluetoothAdapter!!.getRemoteDevice(macAddress)
  288. if (mBluetoothDevice == null) throw IOException("获取不到BluetoothDevice")
  289. mBluetoothDevice!!
  290. } else {
  291. null
  292. }
  293. }
  294. //申请通讯字节长度
  295. fun requestMTP(size: Int = 512): Boolean {
  296. return if (checkBlueToothPermission()) {
  297. mBluetoothGatt?.let {
  298. it.requestMtu(size)
  299. } ?: false
  300. } else {
  301. false
  302. }
  303. }
  304. //连接蓝牙Gatt
  305. fun connect(macAddress: String, callback: BluetoothGattCallback): BluetoothGatt? {
  306. return if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  307. if (mBluetoothDevice == null)
  308. getBlueToothDevice(macAddress)
  309. mBluetoothGatt =
  310. mBluetoothDevice!!.connectGatt(mApplication.applicationContext, false, callback)
  311. mBluetoothGatt
  312. } else {
  313. null
  314. }
  315. }
  316. //断开蓝牙Gatt
  317. fun disConnect() {
  318. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  319. mBluetoothGatt?.let {
  320. it.disconnect()
  321. //调用close()后,连接时传入callback会被置空,无法得到断开连接时onConnectionStateChange()回调
  322. it.close()
  323. }
  324. }
  325. }
  326. //获取蓝牙GattService
  327. fun getBlueToothGattService(gatt: BluetoothGatt): List<BluetoothGattService> {
  328. return gatt.services
  329. }
  330. //发送Characteristic
  331. fun writeCharacteristic(
  332. srvuuid: String,
  333. charuuid: String,
  334. byteArray: ByteArray
  335. ) {
  336. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  337. mBluetoothGatt?.let {
  338. val characteristic =
  339. it.getService(getUUID(srvuuid)).getCharacteristic(getUUID(charuuid))
  340. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
  341. it.writeCharacteristic(
  342. characteristic,
  343. byteArray,
  344. BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
  345. )
  346. } else {
  347. characteristic.setValue(byteArray)
  348. it.writeCharacteristic(characteristic)
  349. }
  350. } ?: {
  351. throw IOException("mBluetoothGatt为空")
  352. }
  353. }
  354. }
  355. //发送Characteristic
  356. fun writeCharacteristic(
  357. characteristic: BluetoothGattCharacteristic,
  358. byteArray: ByteArray
  359. ) {
  360. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  361. // var hexstr = byteArrsyToHexString(byteArray)
  362. // var transbytes = hexstr!!.toByteArray()
  363. mBluetoothGatt?.let {
  364. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
  365. it.writeCharacteristic(
  366. characteristic,
  367. byteArray,
  368. BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
  369. )
  370. } else {
  371. characteristic.setValue(byteArray)
  372. it.writeCharacteristic(characteristic)
  373. }
  374. } ?: {
  375. throw IOException("mBluetoothGatt为空")
  376. }
  377. }
  378. }
  379. fun readCharacteristic(characteristic: BluetoothGattCharacteristic): ByteArray? {
  380. return if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  381. var byteArray: ByteArray? = null
  382. mBluetoothGatt?.let {
  383. it.readCharacteristic(characteristic)
  384. byteArray = characteristic.value
  385. }
  386. byteArray
  387. } else {
  388. null
  389. }
  390. }
  391. //发送返回值sendResponse
  392. fun sendResponse(
  393. device: BluetoothDevice, requestId: Int, offset: Int, value: ByteArray
  394. ) {
  395. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  396. mBluetoothGattServer!!.sendResponse(
  397. device, requestId, BluetoothGatt.GATT_SUCCESS,
  398. offset, value
  399. )
  400. }
  401. }
  402. fun setCharacteristicNotify(characteristic: BluetoothGattCharacteristic, bool: Boolean) {
  403. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  404. mBluetoothGatt?.let {
  405. it.setCharacteristicNotification(characteristic, bool)
  406. }
  407. }
  408. }
  409. fun notifyCharacteristicChanged(
  410. device: BluetoothDevice,
  411. characteristic: BluetoothGattCharacteristic,
  412. byteArray: ByteArray
  413. ) {
  414. if (checkBlueToothPermission(Manifest.permission.BLUETOOTH_CONNECT)) {
  415. //回复客户端,让客户端读取该特征新赋予的值,获取由服务端发送的数据
  416. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
  417. mBluetoothGattServer!!.notifyCharacteristicChanged(
  418. device,
  419. characteristic,
  420. false,
  421. byteArray
  422. )
  423. } else {
  424. characteristic.value = byteArray
  425. mBluetoothGattServer!!.notifyCharacteristicChanged(device, characteristic, false)
  426. }
  427. }
  428. }
  429. }

03

适配器BaseQuickAdapter

4.0版本的BaseQuickAdapter,里面的ViewHolder要自己定义,用法和原来有点不太一样

6ccfbcf7337f99f3db16804e18e242f6.png

41bc85769100e1b49234d69a87e2caa2.png

还有原来我用BaseQuickAdapter中直接用的二级列表,当时也是会有问题,具体问题可以看《Android BaseQuickAdapter3.0.4版本二级列表的使用及遇到的问题》,正好这次服务的列表刷新中又需要实现二级列表,现在我是改为自定义添加了,同样绑定了viewBinding。

40fdcf34d78bbe061f6cd00cb4f5b79e.png

68ca2469271136e75b01b846e913a722.png

04

Fragment中使用ViewBinding注意事项

在Fragment中使用viewBinding,为了防止内存泄漏,Google有标准的写法,不过每个Fragment都这样写比较麻烦,所以这里定义了一个BaseFragment,用于处理viewBinding内存泄露问题。

  1. abstract class BaseFragment<T : ViewBinding> : Fragment() {
  2. private var _binding: T? = null
  3. protected val binding: T get() = _binding!!
  4. abstract val bindingInflater: (LayoutInflater, ViewGroup?, Bundle?) -> T
  5. override fun onCreateView(
  6. inflater: LayoutInflater,
  7. container: ViewGroup?,
  8. savedInstanceState: Bundle?
  9. ): View {
  10. _binding = bindingInflater.invoke(inflater, container, savedInstanceState)
  11. return binding.root
  12. }
  13. override fun onDestroyView() {
  14. super.onDestroyView()
  15. _binding = null
  16. }
  17. }

aaff3b28a61a7b999318d1a01ec83946.png

这样一个基本的蓝牙Ble通讯就完成了。

后续问题

上面的视频中通讯传输是没问题,但是如果发送大点的数据,就不行了,蓝牙BLE发送数据默认单次最大传输20个byte,如果是一般的协议命令,如:开关灯、前进左右等等,是没有问题的,如果是需要发送如:图片、BIN文档、音乐等大数据量的文件,则需要做数据的处理。

基本说考虑到蓝牙发送大数据量时应该通过两个途径结合实现:

  1. 申请修改MTU值,MTU: 最大传输单元(MAXIMUM TRANSMISSION UNIT)

  2. 分包数据发送

简单的通讯Demo实现后,接下来就准备开始研究分包通讯的问题了。

源码地址

https://github.com/Vaccae/AndroidBLEDemo.git

点击原文链接可以看到“码云”的源码地址

b555b12c37de5bcf8a19d835eb445af1.png

f17be96a3f171ddee3a8d5048af22020.png

往期精彩回顾

 

51110eba9a28ec644b8f640c1c437822.jpeg

Android BlueToothBLE入门(一)——低功耗蓝牙介绍

 

 

9132f2df2517286d7a36a8a289f0a1c6.jpeg

Android监听消息(二)——电话及短信监听

 

 

557e546de405bbff90b2fe4225d807f9.jpeg

Android监听消息(一)——应用消息捕获

 

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

闽ICP备14008679号