Why do apps on some Android versions fail to capture audio and video after screen locking or switching to the background?
After screen locking or switching to the background on some Android versions, you may encounter the following issues:
- On Android devices, remote audio is silent or video is not visible within 1 minute of the device being locked.
- When the Android app switches to the background during operation, remote audio is silent.
Reason
- Starting from Android 9, the Android system restricts background apps from accessing user data. For more details, see Android 9 behavior changes.
- Starting from Android 14, the Android system requires apps to specify the necessary foreground service types. If developers set the app's
targetSdkVersion
to34
or higher, the system will trigger a capability check when the app runs on devices with Android 14 or higher to verify if the app has correctly declared its foreground service types. If the app fails to integrate foreground services properly, issues such as microphone capture being ineffective and remote audio being silent may occur when the user switches the app to the background. For more details, see Android 14 behavior changes and Required foreground service types.
Solution
To ensure uninterrupted access to microphone, camera, media playback, and other functionalities when your device is locked or your app is in the background, it's crucial to correctly integrate foreground services. This prevents interruptions in audio and video capture due to system restrictions. Agora provides an example project demonstrating how to integrate foreground services. Here are the steps:
-
In the
AndroidManifest.xml
file, declare the foreground service privilege (FOREGROUND_SERVICE
) and specify the foreground service type (foregroundServiceType
). For real-time audio/video interactive apps, you usually need to specify the microphone (microphone
), camera (camera
), and media playback (mediaPlayback
) service types. The example code is as follows: -
When a service is created, call
startForeground
to promote the specified service to the foreground. The sample code is as follows: -
When the app switches to the background, call
startForegroundService
to start the service to ensure that the service continues to run. The sample code is as follows: