Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do native threads behave different when app is in background?

Tags:

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?

like image 803
Jan Deinhard Avatar asked Jan 26 '17 14:01

Jan Deinhard


People also ask

Which thread is executed in the 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.

How do I run a thread in the background?

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.

What is a background thread?

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.


1 Answers

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.

like image 134
Matthias247 Avatar answered Sep 23 '22 10:09

Matthias247