In my app I use native threads to process audio data. The code looks very much like this:
std::thread([this] () {
while (enabled) {
if (condition()) {
process();
}
usleep(100);
}
});
This works fine when the app is in foreground. In background the processing is not fast enough anymore an I get buffer-underruns. It only works without usleep
in background. The value I pass to usleep
does not make a difference. It does not work with smaller values as well. I also tried std::this_thread::sleep_for(std::chrono::microseconds(100))
but it does not make a difference.
I have to use usleep
or something similar to avoid high CPU usage and thereby to save battery lifetime.
What can I do to make natives threads behave the same when the app is in background?
All Android apps use a main thread to handle UI operations. Calling long-running operations from this main thread can lead to freezes and unresponsiveness. For example, if your app makes a network request from the main thread, your app's UI is frozen until it receives the network response.
thread. run() is going to execute the code in the thread's run method on the current thread. You want thread. start() to run thread in background.
Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down.
It seems like Android sets the Thread priority for background apps lower if not explicitly specified otherwise. This documentation mentions
Generally, threads in the foreground group get about 95% of the total execution time from the device, while the background group gets roughly 5%.
Which would explain your underruns. You should try to increase the priority like it's described there. The linked video also seems helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With