Reputation: 965
I have created the following background thread:
public class loadSomeStuff extends AsyncTask <String, Integer, String>
{
@Override
protected String doInBackground(String... params) {
Intent i = new Intent("com.example.nadir_services.himan.class"); startActivity(i);
return null;
}
}
I also created a button, in which I call this thread:
new loadSomeStuff().execute("");
So, my question is, every time I press this button, will it create a new thread? If so, why is that bad? I mean, what will happen ?
And a side question, I noticed that this is called a "background thread". Does that mean there is another way to create a new thread ? I only know of this way.
Upvotes: 1
Views: 67
Reputation: 8621
will it create a new thread?
No, AsyncTask is added to a pool of threads (initially 4, up to (number of CPU * 2) + 1) which will be used to run your background Task.
why is that bad?
You should not create a new instance of your AsyncTask every time you click the button.. You should declare your instance of AsyncTask outside onClick and only launch it from within that method.
does that mean there is another way to create a new thread ?
Yes. AsyncTask is there to provide you with practical callback methods to know when the task is finished (onPostExecute), execute code before the task runs (onPreExecute), post progress ... The other way is creating a Worker Thread.
Upvotes: 1
Reputation: 8134
Its called the "background thread" because there is a "main" thread which is the UI Thread for Android. This basically controls/operates on what is happening in front of the user.
When you call an async task - background thread - means the operation associated with your task is broken down into what is happening in operation and meanwhile what is happening in foreground for the User.
To understand the difference exactly, please have a look at:
http://developer.android.com/guide/components/processes-and-threads.html
http://developer.android.com/training/multiple-threads/communicate-ui.html
http://developer.android.com/reference/android/os/AsyncTask.html
What is the Android UiThread (UI thread)
Upvotes: 0
Reputation: 12587
no, AsyncTask
is constructed with ThreadPool of 4 threads and by default the system chooses one of those threads to run on.
In general, if you want to avoid memory issues, you should initialise the AsyncTask outside from the onClick and execute it from there instead of creating a new one every time like this:
private loadingTask = new LoadSomeStuff();
@Override
public void onClick(View v) {
loadingTask.execute("");
}
edit, for future reference, please have a look at the source code for AsyncTask
Upvotes: 5