问题
Android docs indicate that Oreo has new restrictions on background execution: https://developer.android.com/about/versions/oreo/background. This seems reasonable and they're clearly aiming to make their platform more like iOS and prevent apps running rampant in the background.
The thing that's unclear to me (in fact, not documented at all) is what can you do on a thread when the UI goes to the background. Specifically,
GIVEN I create a thread with
new Thread(() -> {
// Naughty thread doing something forever
}).start();
AND I send the app to the background
THEN ...what happens to that thread?
I've created very simple code to do this and my thread has been happily churning out to logcat for 10+ minutes with no issues.
Does anyone have any clear information on what restrictions there are on such threads? I would have thought that since Android restricts what a background service can do that it would also restrict what such threads can do.
Note that we have no plans to write an app which does anything like this. We just want to be able to write safe code which doesn't cause issues on newer versions of android. On iOS, if you go to the background then you get a period of grace to finish off whatever you're doing (and you can ask for more time) but eventually your thread will be suspended.
回答1:
Does anyone have any clear information on what restrictions there are on such threads? I would have thought that since Android restricts what a background service can do that it would also restrict what such threads can do.
There are no restrictions as such on how long such threads can run. As long as your app is running in background, you can continue to execute Thread in background
However, you need to consider how to gracefully terminate/release the Thread, since the Thread won't run endlessly. If OS needs to relinquish memory during memory crunch then the process of your app hosting this background Activity will be terminated, eventually destroying the thread. If not handled properly, this would lead to Thread/memory leaks.
回答2:
As @Sagar's answer mentioned, while the system may selectively terminate "background services", it does not selectively terminate individual "background threads".
But your question has more to it than just avoiding termination; you expect your thread to execute continuously. Other answers on this page don't mention WakeLocks, and there are some misleading comments in that regard, so I will address that here.
We are dealing with two separate issues: App termination, and device sleep.
App termination: Android terminates apps to free up resources -- preferring apps that are in the background (e.g., apps that are not on screen, and that don't contain a foreground service). When your app is terminated, all its threads are terminated too.
Device sleep: Android will pause your thread, as it pauses all threads, when the device goes to sleep. That's how so much of the battery savings are realized on mobile devices: The CPU goes into a low-power "standby" mode, and ceases executing instructions. Even though the device may be sleeping, your app (and its threads) continue to exist.
- Use a foreground service to stop your app from being terminated after it leaves the screen.
- Use a
WakeLock
(PARTIAL_WAKE_LOCK) to keep the CPU in a state where it can execute, even though the screen may be off.
Having a foreground service does not stop the device from going to sleep. Similarly, holding a WakeLock
does not prevent your app from being terminated. Note that newer versions of Android can ignore WakeLocks in doze. See here for one approach to dealing with this.
Having a Foreground service does not guarantee your code will execute any faster than with a background service. Foreground services do not "terminate" doze.
If your logs continued to print out for 10 minutes, I would suggest it's probably because your device was plugged in. On most Android devices, the CPU stays awake when plugged in (even though the screen may be off).
回答3:
According to my tests on emulator APIs 26 and 27, a started thread will continue to work as long as the app is still in the background and not terminated, and the system doesn't decide to kill the thread or terminate the app.
I even forced the emulators to deep doze using:
$ adb shell dumpsys deviceidle force-idle
Yet, still the thread was running. However, this does not happen on real physical devices. Threads pause when entering doze. So based on experience, do not fully trust emulators.
So, your observations were normal as you mentioned in your question.
As for this:
Does anyone have any clear information on what restrictions there are on such threads? I would have thought that since Android restricts what a background service can do that it would also restrict what such threads can do.
Well, threads had always been less of a concern themselves than services when it comes to eating up memory and battery. Pre-Marshmallow, services could keep doing work forever even if you close the app and if the system kills it to reclaim memory, they restart again after a while (START_STICKY). So, this behavior was dangerous when it comes to battery consumption and resource consumption.
On the other hand, threads terminate as soon as the app is terminated and they do not start automatically again. Also, the system would rather terminate a background app having no service running even if it had lots of running threads, than one that has a service running.
Starting Marshmallow, they introduced Doze mode to pause almost everything only when the phone goes to sleep to save battery. But, still that didn't fix the problem of apps that the user is not currently using from doing intensive work in the background (Services) as soon as the device exits doze and making performance of the user's running app deteriorate.
So, starting Oreo they imposed restrictions on services of apps that are not in the foreground as they are the main reason of causing performance hazards. So, maybe in the future they will impose restrictions on the threads of apps when they are in the background too, to even further improve resource consumption.
回答4:
As long as you start the thread when the App is in foreground, the thread might(I mean might) continue to run when the App goes to background.
BUT, the thread would be killed if the phone is running low on Memory and the System decides to reclaim memory. This is prone to happen on lower end devices much frequently. You need to have a look at Android GO.
Alternative : By all means, you can leverage JobScheduler or the new and improved WorkManager to achieve the same functionality which you might be wanting to achieve by running a thread. Since JobScheduler and WorkManager are managed by the Android System, you can be guaranteed that your functionality keeps working irrespective of the constrains on the System. Additionally, you can specify contains like Network/Battery when you are using JobScheduler/WorkManager. This is something you don't get when using a Thread.
来源:https://stackoverflow.com/questions/51296962/what-happens-if-i-run-an-android-thread-in-the-background-indefinitely