文档中心
互动直播 (Legacy)
Console 官网 社区 技术支持

为什么 Android 9 应用锁屏或切后台后采集音视频无效?

分类: 其他问题    平台: Android   最后更新时间: 2023/06/24 23:27:26

问题现象:Android 9 设备锁屏 1 分钟内,音频无声或看不到视频。

问题原因:从 Android 官网来看,这是系统强制限制。原文如下:

Limited access to sensors in background
Android 9 limits the ability for background apps to access user input and sensor data. If your app is running in the background on a device running Android 9, the system applies the following restrictions to your app:

  • Your app cannot access the microphone or camera.
  • Sensors that use the continuous reporting mode, such as accelerometers and gyroscopes, don't receive events.
  • Sensors that use the on-change or one-shot reporting modes don't receive events.
    If your app needs to detect sensor events on devices running Android 9, use a foreground service.

详见 Android 行为变更

解决方案: 目前 Android 官网没有明确说明后台采集声音或视频应如何处理,但使用前台服务可以让你的应用程序将继续在后台运行,并能够采集声音或视频数据,而不会受到系统限制或停止的影响。

你可以参考以下步骤来使用前台服务:

  1. 创建前台服务。在应用程序的 manifest 文件中声明前台服务,并通过 startForeground() 方法将服务设置为前台服务。
  2. 在应用程序的manifest 文件中添加 foregroundServiceType="microphone|mediaPlayback" 属性,这样可以让系统知道该服务需要持续运行,并且需要使用麦克风或媒体播放器,从而避免被系统限制。
如果你的 app 的 targetSdkVersion 是 31及以上版本,需要设置 foregroundServiceTypetargetSdkVersion 31 以下的版本,直接通过 startForeground 方法启动前台服务即可。

官网文档请参考:https://developer.android.com/reference/android/app/Service