phone 屏幕关闭时核心蓝牙扫描外围设备

Core Bluetooth scan for peripherals while the phone's screen is off

当应用程序处于后台并且 phone 的屏幕关闭时,我需要继续扫描来自外围设备的广播。从后台扫描成功,但当 phone' 屏幕关闭时,我无法扫描(无法触发 didDiscoverPeripheral)广播。

到目前为止,我已经在 applicationDidEnterBackground 中实现了 beginBackgroundTaskWithExpirationHandler,这就是我能够在后台进行扫描的方式。那么我应该怎么做呢?

这是不可能的。 当你勾选 'Uses Bluetooth LE accessories''Acts as a Bluetooth LE accessory' 时,当 iPhone 屏幕灯关闭时,核心蓝牙框架停止广播和扫描。一旦屏幕灯重新亮起,它就会恢复 advertising/scanning。这是 iOS.

中可实现的最大可能场景

如果你想更进一步,你可以使用 beginBackgroundTaskWithExpirationHandler - https://developer.apple.com/documentation/uikit/uiapplication/1623031-beginbackgroundtaskwithexpiratio 但这几乎不能持续 3 分钟。这 3 分钟从应用程序从前台转到后台开始。

为了节省电池电量,iOS 似乎会自动关闭 BLE 硬件,并在设备 moves/screen 唤醒后立即恢复。因为当屏幕关闭时,用户无论如何都不会使用 iPhone。

编辑:除非连接了设备,例如耳机 - 虽然不是广告,但现有连接的设备可以共享数据。