简体   繁体   English

在 android 中的应用程序启动期间,有没有办法知道设备的蓝牙连接状态?

[英]Is there way to know Bluetooth connection status to a device during app startup in android?

I have a use case where I want to know whether my Bluetooth is connected to any other device during my app startup time.我有一个用例,我想知道我的蓝牙在我的应用程序启动期间是否连接到任何其他设备。 Like I know we have a broadcast receiver to listen to connectivity status changes but specifically, I want to know at the app starting time whether it is connected to any other device or not.就像我知道我们有一个广播接收器来监听连接状态的变化,但具体来说,我想在应用程序启动时知道它是否连接到任何其他设备。 More specifically I have a wearOS watch and I'm running the app overwatch so I want to check whether it's connected to the phone or not更具体地说,我有一个wearOS手表,我正在运行应用程序,所以我想检查它是否连接到手机

TL;DR: There is no direct way to find out the connected devices for non-system apps. TL;DR:没有直接的方法来找出非系统应用程序的连接设备。 But there is a hack to figure out the connected devices, with less guarantee.但是有一个黑客可以找出连接的设备,而且保证较少。

System apps such as Android settings use BluetoothDevice.isConnected() API to get the current connection status of paired/bonded devices. Android 设置等系统应用程序使用BluetoothDevice.isConnected() API 获取配对/绑定设备的当前连接状态。 This system API can't be used by non-system apps.此系统 API 不能被非系统应用程序使用。

Here is how a non-system app can figure out connected device:以下是非系统应用程序如何识别连接的设备:

  1. Make sure all required bluetooth permission are mentioned in manifest and granted.确保清单中提到并授予所有必需的蓝牙权限
  2. Get list of paired/bonded devices by calling BluetoothAdapter.getBondedDevices()通过调用BluetoothAdapter.getBondedDevices()获取配对/绑定设备列表
  3. Now we will try to establish socket connection to each device via RFCOMM socket .现在我们将尝试通过RFCOMM 套接字建立到每个设备的套接字连接。
  4. If the API throws any error, then most probably the devices aren't connected, or can't connect.如果 API 抛出任何错误,则很可能设备未连接或无法连接。
  5. Now if the socket connection is established then there is a chance the devices are connected.现在,如果建立了套接字连接,则设备可能已连接。 To verify if device is connected by calling isConnected() on the socket connection.通过在套接字连接上调用isConnected()来验证设备是否已连接。

This way you can identify all the connected devices.这样您就可以识别所有连接的设备。 Now this is a resource intensive task.现在这是一项资源密集型任务。 I would recommend to do it once at the beginning.我建议一开始就做一次。 Post that until your app is active listen to ACTION_ACL_CONNECTED and ACTION_ACL_DISCONNECTED broadcasts.发布,直到您的应用程序处于活动状态,收听ACTION_ACL_CONNECTEDACTION_ACL_DISCONNECTED广播。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM