user1888162
user1888162

Reputation: 1735

Android AsyncTask: Will methods that are called inside doInBackground() executed in main or background thread?

Lets say i have a class which contains inner class that is named fooTask that extends AsyncTask and a method named getFoo() that returns some int value. If i call this getFoo() method inside AsyncTask's doInBackground() method, will this getFoo() method be executed in main or background thread?

public class SomeClass extends Activity {


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        fooTask task = new fooTask();
        task.execute();
    }

    private class fooTask extends AsyncTask<Void, Void, Integer>{

        @Override
        protected Integer doInBackground(Void... params) {
            int foo = getFoo();
            return foo;
        }

    }

    private int getFoo(){
        // Will this method be executed in main or background thread?
        return 1;
    }
}

Upvotes: 2

Views: 2433

Answers (4)

Dmitry Zaytsev
Dmitry Zaytsev

Reputation: 23972

It is not a method which runs in background (or main) thread - it's bytecode. However, bytecode can be scheduled for execution in any thread.

In particular, if you'll call doInBackground directly from the main thread - it will run on the main thread. If you'll leave implementation as it is (won't access this method directly) - it will run in background thread.

Upvotes: 1

Matias Elorriaga
Matias Elorriaga

Reputation: 9150

everything inside doInBackground runs in the background, unless you wrap some block of code inside runOnUiThread

Upvotes: 1

Awanish
Awanish

Reputation: 48

Everything you write inside doInBackground runs in the background. It has no connection with your GUI or different thread.

Upvotes: 1

Kiloreux
Kiloreux

Reputation: 2256

It will be executed in background thread as mentioned in the AsyncTask documentation ,

This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

link to android documentation here

Upvotes: 1

Related Questions