Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I run an Android thread in the background indefinitely

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.

like image 401
Andrew Parker Avatar asked Oct 29 '22 08:10

Andrew Parker


1 Answers

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.

like image 199
Sagar Avatar answered Nov 15 '22 05:11

Sagar