Reputation: 1338
I have a launcher style app from within which you can launch another app. While that app is launched, I want my app to make note of some things, basically record time etc.
So I have a segment of code whose structure basically looks like this:
appSelectedListener{
runSelectedApp;
private class Background extends AsyncTask<Void, Void, Void>{
protected void doInBackground(){
//executable code
}
}
}
Something alone those lines, I'm sorry if the code is off but I don't actually have anything written yet I just want to get a handle on this stuff first. My question is, when the selected app is brought to the foreground, my app goes to the background. Does the executable code in doInBackground() still get run though? Or would my app necessarily have to be in the foreground?
Upvotes: 1
Views: 419
Reputation: 8641
To clarify: it's a bit of a misnomer to say that doInBackground() "runs in the background". It runs on a separate thread from the UI thread, but in the same process as the rest of your app (except for any components that you run in a separate process). The UI thread is the highest priority, and the Android system takes steps to ensure that other threads and processes don't interfere with it.
When an event causes a new activity's UI thread to take priority, all other UI threads pause. Other non-UI threads may or may not continue, depending on various factors.
Also, remember that when the user changes the device's orientation, Android's default behavior is to call the onDestroy() followed the onCreate() methods for the activity. This will destroy the AsyncTask object, which destroys the non-UI thread being used to do work asynchronously, which in effect cancels the execution of the code in doInBackground().
For this reason, you should use AsyncTask to do short operations that you don't mind repeating if they get cancelled before finishing. Long-running operations (such as downloading from a server) should be done by an IntentService or sync adapter.
Upvotes: 1
Reputation: 1007218
Does the executable code in doInBackground() still get run though?
Usually. The behavior of threads you fork is not immediately affected by foreground/background considerations.
Eventually, the process for your backgrounded app will be terminated, to free up memory for other apps, or because the user requested that the process be terminated. At that point, all background threads (and everything else you have in RAM) go away. If you have an AsyncTask
that has not yet gotten to doInBackground()
, doInBackground()
will not be called in this case.
Upvotes: 2