简体   繁体   English

当蓝牙设备自动与系统配对/连接时,Android会收到回叫吗?

[英]Android receive callback when bluetooth device is paired/connected by the system automatically?

Is there any way to receive a callback when Android automatically pairs/connects to a bluetooth device, for instance my car, and not having the app already started/open (some kind of broadcast)? 有什么方法可以在Android自动配对/连接到蓝牙设备(例如我的车),而不是已经启动/打开(某种广播)的应用程序接收回叫 I have had thoughts about a service that periodically scans for devices and sees if they are already bonded, but that feels ineffective as Android already does this: it will automatically connect to for instance my car when I am in range. 我已经想过定期扫描设备并查看它们是否已经绑定的服务,但是因为Android已经这样做了,感觉无效:当我在范围内时它会自动连接到我的车。 The idea is to start a specific job when I am in range of my car, and stop the job when I am out of range of my car, without having to start the app or have it open. 这个想法是当我在我的汽车范围内时开始一项特定的工作,并在我超出我的汽车范围时停止工作,而无需启动应用程序或打开它。

My initial thought was that there should be some kind of broadcast one could register to, to know when the device is "connected", and in that listener just start the job for some time or until the device is "disconnected". 我最初的想法是,应该有一种可以注册的广播,知道设备何时“连接”,并且该侦听器只是启动作业一段时间或直到设备“断开连接”。 Note that having your phone in your pocket and not taking it up is a necessity. 请注意,将手机放在口袋中而不是拿起手机是必要的。 I have only seen examples that does this if the app is already open, by listening on state changes. 我只看过一些示例,如果应用程序已经打开,通过监听状态更改来执行此操作。 Is this possible to not have the app open and only be "event driven" and listen on broadcasts? 这可能是没有应用程序打开,只是“事件驱动”和收听广播?

Try the following code: 请尝试以下代码:

IntentFilter actionChangeFilter = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        mContext.registerReceiver(btDeviceConnectChangedReceiver, actionChangeFilter);

You can listen for the ACTION_STATE_CHANGED broadcast of the BluetoothAdapter. 您可以收听BluetoothAdapter的ACTION_STATE_CHANGED广播。

See here for details 详情请见此处

Edit: 编辑:

The above is for changes of state of adapter. 以上是适配器状态的变化。 To listen to new connections etc use those listed here: BluetoothDevice 要收听新连接等,请使用此处列出的内容: BluetoothDevice

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

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