0

Within an Asynctask I call a method, i mean from within doInBackgroud() { ...code goes here ... }, I call a method that is ..

A) .. within the async task class

B) .. in a different class

Is this method-call still executed in the thread of the asynctask?

I am wondering, because it is often said that "only code inside doInBackgroud() { ...code goes here ... } is executed in a different thread.

Florian Zidar
  • 71
  • 1
  • 7

3 Answers3

1

Yes, the method call is executed in the thread of the asynctask. The asynctask would be pretty useless if unable to invoke methods on other classes. Furthermore, if the doInBackground method (frequently used to make web requests) would run in the main thread, the Android would throw an exception (NetworkOnMainThreadException).

rmsc
  • 13
  • 3
1

I am wondering, because it is often said that "only code inside doInBackgroud() { ...code goes here ... } is executed in a different thread.

When your application is started up, a thread is created called the UI thread (also known as the ‘main’ thread). This thread dispatches all of the events to the widgets and whatnot on your application.

The AsyncTask will execute onPreExecute and onPostExecuteon the UI thread. doInBackground() on the other-hand is invoked on the background thread and will return back to the main thread once completed.

Smittey
  • 2,475
  • 10
  • 28
  • 35
1

Calls made (either directly or indirectly) from within doInBackground() are automatically run in the background thread.

There are ways to force some code to run within the main UI thread (for example, see this question), but that has to done explicitly.

Community
  • 1
  • 1
cybersam
  • 63,203
  • 6
  • 53
  • 76