前台服务重启后多次接收BluetoothGattCallback

2024-04-10

我正在使用支持 BLE 的硬件,并使用 Android 的前台服务与硬件进行通信。 前台服务负责处理 BLE 相关事件,并且在一段时间内按照要求工作得很好,但不知何故,如果前台服务被终止或 BLE 连接由于任何原因而中断,则应用程序会尝试再次重新连接到 BLE,然后BLE 回调开始从 BluetoothGattCallback 获取重复事件,也就是说,即使硬件向蓝牙发送单个事件,但 Android BluetoothGattCallback 会收到相同事件的多个回调,这会导致我们的实现中出现很多错误。

作为参考,请查看以下日志,

Following are methods and callbacks from my foreground service,

BLEManagerService: *****onDescriptorWrite: 0*****<br>
BLEManagerService: *****onDescriptorWrite: 0*****<br>
BLEManagerService: *****onDescriptorWrite: 0*****<br>
BLEManagerService: Firmware: onCharacteristicRead true<br>
BLEManagerService: *****onDescriptorWrite: 0*****<br>
BLEManagerService: Firmware: onCharacteristicRead true<br>
BLEManagerService: *****onCharacteristicRead: 0*****<br>
BLEManagerService: *****onCharacteristicRead: 0*****<br>
override fun onCreate() {
    super.onCreate()

    mBluetoothGatt?.let { refreshDeviceCache(it) }

    registerReceiver(btStateBroadcastReceiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED))
}

    /**
 * Start BLE scan
 */
private fun scanLeDevice(enable: Boolean) {
    if (enable && bleConnectionState == DISCONNECTED) {
        //initialize scanning BLE
        startScan()
        scanTimer = scanTimer()
    } else {
        stopScan("scanLeDevice: (Enable: $enable)")
    }
}

private fun scanTimer(): CountDownTimer {
    return object : CountDownTimer(SCAN_PERIOD, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            //Nothing to do

        }

        override fun onFinish() {
            if (SCAN_PERIOD > 10000 && bleConnectionState == DISCONNECTED) {
                stopScan("restart scanTimer")
                Thread.sleep(200)
                scanLeDevice(true)
                SCAN_PERIOD -= 5000
                if (null != scanTimer) {
                    scanTimer!!.cancel()
                    scanTimer = null
                }
                scanTimer = scanTimer()
            } else {
                stopScan("stop scanTimer")
                SCAN_PERIOD = 60000
            }
        }
    }
}


//Scan callbacks for more that LOLLIPOP versions
private val mScanCallback = object : ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult) {
        val btDevice = result.device
        if (null != btDevice) {
            val scannedDeviceName: String? = btDevice.name

            scannedDeviceName?.let {
                if (it == mBluetoothFemurDeviceName) {
                    stopScan("ScanCallback: Found device")
                    //Disconnect from current connection if any
                    mBluetoothGatt?.let {it1 ->
                        it1.close()
                        mBluetoothGatt = null
                    }
                    connectToDevice(btDevice)
                }
            }
        }
    }

    override fun onBatchScanResults(results: List<ScanResult>) {
        //Not Required
    }

    override fun onScanFailed(errorCode: Int) {
        Log.e(TAG, "*****onScanFailed->Error Code: $errorCode*****")
    }
}

/**
 * Connect to BLE device
 * @param device
 */
fun connectToDevice(device: BluetoothDevice) {
    scanLeDevice(false)// will stop after first device detection

    //Stop Scanning before connect attempt
    try {
        if (null != scanTimer) {
            scanTimer!!.cancel()
        }
    } catch (e: Exception) {
        //Just handle exception if something
        // goes wrong while canceling the scan timer
    }
    //Stop scan if still BLE scanner is running
    stopScan("connectToDevice")
    if (mBluetoothGatt == null) {
        connectedDevice = device
        if (Build.VERSION.SDK_INT >= 26)
            connectedDevice?.connectGatt(this, false, mGattCallback)
    }else{
        disconnectDevice()
        connectedDevice = device
        connectedDevice?.connectGatt(this, false, mGattCallback)
    }
}

/**
 * Disconnect from BLE device
 */
private fun disconnectDevice() {
    mBluetoothGatt?.close()
    mBluetoothGatt = null

    bleConnectionState = DISCONNECTED
    mBluetoothManager = null
    mBluetoothAdapter = null
    mBluetoothFemurDeviceName = null
    mBluetoothTibiaDeviceName = null
    connectedDevice = null
}

/****************************************
 * BLE Related Callbacks starts         *
 * Implements callback methods for GATT *
 ****************************************/
// Implements callback methods for GATT events that the app cares about.  For example,
// connection change and services discovered.
private val mGattCallback = object : BluetoothGattCallback() {

    /**
     * Connection state changed callback
     */
    override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            mBluetoothGatt = gatt                
            //Stop Scanning before connect attempt
            try {
                if (null != scanTimer) {
                    scanTimer!!.cancel()
                }
            } catch (e: Exception) {
                //Just handle exception if something
                // goes wrong while canceling the scan timer
            }
            stopScan("onConnectionStateChange")// will stop after first device detection

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED || status == 8) {

            disconnectDevice()
            Handler(Looper.getMainLooper()).postDelayed({
                initialize()
            }, 500)

        }
    }

    /**
     * On services discovered
     * @param gatt
     * @param status
     */
    override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
        super.onServicesDiscovered(gatt, status)

    }

    override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
        super.onDescriptorWrite(gatt, descriptor, status)

    }

    /**
     * On characteristic read operation complete
     * @param gatt
     * @param characteristic
     * @param status
     */
    override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
        super.onCharacteristicRead(gatt, characteristic, status)

    }

    /**
     * On characteristic write operation complete
     * @param gatt
     * @param characteristic
     * @param status
     */
    override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
        super.onCharacteristicWrite(gatt, characteristic, status)
        val data = characteristic.value
        val dataHex = byteToHexStringJava(data)
    }

    /**
     * On Notification/Data received from the characteristic
     * @param gatt
     * @param characteristic
     */
    override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
        super.onCharacteristicChanged(gatt, characteristic)
        val data = characteristic.value
        val dataHex = byteToHexStringJava(data)


    }

    override fun onReadRemoteRssi(gatt: BluetoothGatt, rssi: Int, status: Int) {
        super.onReadRemoteRssi(gatt, rssi, status)
        val b = Bundle()
        b.putInt(BT_RSSI_VALUE_READ, rssi)
        receiver?.send(APP_RESULT_CODE_BT_RSSI, b)
    }
}


/**
 * Bluetooth state receiver to handle the ON/OFF states
 */
private val btStateBroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)

        when (state) {

            BluetoothAdapter.STATE_OFF -> {
                //STATE OFF
            }

            BluetoothAdapter.STATE_ON -> {
                //STATE ON
                btState = BT_ON
                val b = Bundle()
                receiver?.send(APP_RESULT_CODE_BT_ON, b)
                initialize()
            }

            BluetoothAdapter.STATE_TURNING_OFF -> {
                //Not Required

            }

            BluetoothAdapter.STATE_TURNING_ON -> {
                //Not Required

            }
        }
    }
}

private fun handleBleDisconnectedState() {
    mBluetoothGatt?.let {
        it.close()

        receiver?.send(DISCONNECTED, b)
        Handler(Looper.getMainLooper()).postDelayed({
            mBluetoothManager = null
            mBluetoothAdapter = null
            mBluetoothFemurDeviceName = null
            mBluetoothTibiaDeviceName = null

            mBluetoothGatt = null
        }, 1000)
    }
}


/****************************************
 * BLE Related Callbacks End  ***
 ****************************************/

/****************************************************
 * Register Receivers to handle calbacks to UI    ***
 ****************************************************/

override fun onDestroy() {
    super.onDestroy()

    try {
        mBluetoothGatt?.let {
            it.close()
            mBluetoothGatt = null
        }
        unregisterReceivers()
        scanTimer?.cancel()

    } catch (e: Exception) {
        e.printStackTrace()
    }
}

override fun onTaskRemoved(rootIntent: Intent?) {
    super.onTaskRemoved(rootIntent)
    Log.e(TAG, "onTaskRemoved")
    stopSelf()
}

/**
 * Unregister the receivers before destroying the service
 */
private fun unregisterReceivers() {
    unregisterReceiver(btStateBroadcastReceiver)
}

companion object {
    private val TAG = BLEManagerService::class.java.simpleName
    private var mBluetoothGatt: BluetoothGatt? = null
    var bleConnectionState: Int = DISCONNECTED
}

}


不要在 onConnectionStateChange 中设置 mBluetoothGatt = gatt。而是从 connectGatt 的返回值中设置它。否则,您可能会创建多个 BluetoothGatt 对象而不关闭以前的对象,从而获得多个回调。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

前台服务重启后多次接收BluetoothGattCallback 的相关文章

  • 将项目升级到Android Studio 1.0(Gradle问题)

    首先 我对 android 开发 android studio gradle 非常陌生 所以如果我问了一个愚蠢的问题 请原谅我 我的团队一直在使用 android studio 的 beta 版本开发一个项目 我刚刚安装了新版本 1 0 并
  • 如何从该 JAVA 文件中提取 Delphi 类以与 Android 一起使用?

    我的Delphi XE7项目需要与FTDI FT311 Android 配件芯片 http www ftdichip com Products ICs FT311D html 他们帮助提供了一个 Android 演示 其中包括他们的 JAV
  • 使用 dpi 与 dp 缩放图像之间的差异

    我拥有所有由九个补丁位图组成的 dpi 可绘制目录 xxhdpi 和 xxxhdpi 是否必要 可绘制目录中的可绘制资源文件可检索所有缩放的位图 并且我使用可绘制资源文件 现在 我的问题是我还根据大小 小 正常等 创建了 缩放 布局目录 其
  • 如何在android中压缩和解压png图像

    您好 在我的应用程序中 当我单击 zip 按钮时 我需要压缩图像文件 当我单击解压缩按钮时 我需要解压缩文件 我尝试使用下面的代码来压缩图像 但我的问题是当我单击 zip 按钮时 正在创建 zip 文件 但之后在使用 winzip 软件的系
  • 导入已经创建的sqlite数据库(xamarin)

    我正在使用 Xamarin 想知道如何导入我已经创建的 sqlite 数据库 到目前为止 我已将其添加到资产文件夹中 但不知道下一步从哪里开始 string localPath Path Combine System Environment
  • onScale 事件后触发奇怪的 onScroll 事件

    我有一个同时使用 SimpleOnScaleGestureListener 和 SimpleOnGestureListener 的应用程序 每当我进行捏缩放时 我都会得到预期的 onScale 但是当我抬起时 我会看到一个奇怪的 onScr
  • Android Fragment onCreateView 与手势

    我正在尝试在片段中使用手势 我在 FragmentActivity 中有以下内容来处理我的详细信息片段 我试图发生的情况是 当在视图上检测到滑动时 将该视图内的数据替换为上一个或下一个条目 如果有更好的方法来处理这个问题 我完全同意 然而
  • 在选项卡上保存数据

    我有 3 个选项卡 每个选项卡都有一个单独的活动 我想在用户单击任一选项卡上的 保存 时保存数据 有几个选项可供选择 共享首选项 全局变量或将对象保存在上下文中 编辑 我必须保存图像和文本字段 Android 共享首选项 https sta
  • 来自相机的 MediaCodec 视频流方向和颜色错误

    我正在尝试流式传输视频捕获直接从相机适用于 Android 设备 到目前为止 我已经能够从 Android 相机捕获每一帧预览帧 byte data Camera camera 函数 对数据进行编码 然后成功解码数据并显示到表面 我用的是安
  • 屏幕开/关检测

    在这里 我试图确定屏幕是否打开 但按下电源锁定 解锁按钮时它似乎不起作用 应用程序运行没有错误 但 if else 中的代码似乎没有效果 Edited现在代码可以工作了 谢谢Olgun 但媒体播放器播放不会停止 并且每次在屏幕上 离屏时都会
  • 是否可以使用 CardView 为浮动操作按钮制作阴影?

    I know CardView不是为此而设计的 但理论上如果cardCornerRadius view size 2它应该导致圆圈 我错过了什么吗 绘制真实的动画阴影并不困难 您可以尝试在 Froyo 等任何 Android 设备上实现 L
  • 我在 PopupMenu 中使用 ShareActionProvider,但显示两个 PopupMenu?

    我在 PopupMenu 中使用 ShareActionProvider 但是当我单击共享菜单项时 它会在屏幕上显示两个 PopupMenus 一个被另一个覆盖 一个显示应用程序图标和名称 另一个仅显示应用程序名称 除了这个问题之外 它工作
  • 如何在 Android 上将动态 alpha 遮罩应用于文本

    I want to make a dynamic alpha mask with drawable shapes as circles or whatever and apply it to a drawed text on Android
  • Android Gradle 同步失败:无法解析配置“:classpath”的所有工件

    错误如下 Caused by org gradle api internal artifacts ivyservice DefaultLenientConfiguration ArtifactResolveException Could n
  • 在 Nougat 7.1.1 中点击应用程序快捷方式时出现应用程序未安装错误

    我在向现有应用程序添加静态应用程序快捷方式时遇到一些问题 我按照以下步骤操作https developer android com guide topics ui shortcuts html https developer android
  • 在 Android 手机中通过耳机插孔发送数据

    我目前正在处理一个新项目 我必须通过具有特定电压的耳机插孔发送数据 然后我可以在该电压上工作 所以这里我需要根据我的数据来编程具体电压 我是否可以在android中访问耳机的输出电压 然后创建一个应用程序来控制该电压 这是一篇讨论此问题的
  • 使用 DataBindingComponent 的 Inflate 方法

    当 Glide 成功渲染图像后 我在更新文本视图时看到此错误 致命异常 java lang IllegalStateException 必需 CustomBinding 类中的 DataBindingComponent 为 null 绑定适
  • R.java是手动修改的!恢复到生成的版本

    我在布局中添加了一个 xml 文件 之后这个错误就来了 但问题是我还没有接触过 R java 文件 现在 在我的新活动中 我要将其内容视图设置为我新创建的 xml 文件 但是当我执行 R layout 时 新创建的 xml 不会出现在建议中
  • 如何在布局编辑器中模拟沉浸式模式

    我想在布局编辑器中全屏查看我的布局 我正在使用 eclipse 插件 我已经通过选择隐藏了 ActionBar NoActionBar组合中的主题 但导航栏是一个不同的故事 AFAIK 它只能使用代码中的标志来隐藏 我需要在活动 xml 文
  • 我应该如何在 Android 上使用 Retrofit 处理“无互联网连接”

    我想处理没有互联网连接的情况 通常我会运行 ConnectivityManager cm ConnectivityManager context getSystemService Context CONNECTIVITY SERVICE N

随机推荐