I have an android app that runs a foreground service that records audio. To do this I use an AudioRecord
object that I initialize like so:
this.audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampRate, rec_channel_code, _encoding, BUFFER_SIZE);
The app is also configured to run automatically on BOOT_COMPLETED
.
When I run the app manually, either by pressing the icon or from Android Studio, everything works great, audio is recorded and there's no issue - So I know I'm opening the recorder correctly, and I have permissions to do it.
The problem is, when the app runs automatically after boot, it doesn't work at all. I get several error messages, the first one being:
permission denied: recording not allowed for uid 10388 pid 7413
And then there's these ones, that are probably a result of the permission error:
E/AudioRecord: createRecord_l(0): AudioFlinger could not create record track, status: -1
E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -1.
E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
If I then stop the service and run it manually again, it works fine. It doesn't even ask for permissions, because it has them already.
I'm running Android 11, but I have no idea if this happens in previous versions.
So I guess my question is, is it even possible to record audio from a foreground service that runs automatically on boot? And if it is, how do I make it happen?
Things I've tried so far:
Activity
that activates the ForegroundService
, instead of the service itself, when activating from the BootReceiver
(so it can request permissions again, if needed) - This doesn't work as the ActivityManager kills my activity immediatelyAny help would be appreciated, Thanks!
After further research, it seems that according to the documentation, it simply isn't possible.
To help protect user privacy, Android 11 (API level 30) introduces limitations to when a foreground service can access the device's location, camera, or microphone. When your app starts a foreground service while the app is running in the background, the foreground service has the following limitations:
- Unless the user has granted the ACCESS_BACKGROUND_LOCATION permission to your app, the foreground service cannot access location.
- The foreground service cannot access the microphone or camera.
The user has to have some kind of active interaction with the app to allow the foreground service to start recording, such as displaying a notification that says "Tap here to start recording".