1

While reading the documentation, I found that The AsyncTask class must be loaded on the UI thread. But I am surprised that AsyncTask can also be executed from the worker thread.

So the question is:

  1. If AsyncTask can also execute from the background thread, Why in the documentation they are saying just opposite to it.

  2. How could it possible to have context on onPostExecute.?

    new Thread(new Runnable() {
        @Override
        public void run() {
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    return null;
                }
    
                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
                    Toast.makeText(getBaseContext(), "in AsyncTask...", Toast.LENGTH_SHORT).show();
                }
            }.execute();
        }
    }).start();
    
Akhilesh Dhar Dubey
  • 2,152
  • 2
  • 25
  • 39
  • 1
    you are slightly misunderstood it here! AsyncTask must be triggered from main thread (you can say UI thread too). and moreover it is running in worker thread (you can say separate thread too) – Radhey Apr 30 '18 at 10:14
  • 1
    `AsyncTask must be triggered from main thread`. Well OP just showed code to execute such a task from a worker thread. So please react to the point. @Radhey. – greenapps Apr 30 '18 at 10:56
  • refer this https://stackoverflow.com/a/4918811/1848157 and https://www.quora.com/in/How-many-threads-are-there-in-AsyncTask-on-Android , gives you some useful information. – Radhey Apr 30 '18 at 11:13
  • @Radhey I am not talking about how many threads are there in asynckTask, But my question is about the execution of asyncTask from the worker thread. – Akhilesh Dhar Dubey May 02 '18 at 09:05

2 Answers2

0

The AsyncTask Android class lets us sort of bind background tasks to the UI thread. So using this class, you can perform background operations and then publish the results to the UI thread that updates the UI components.

you can understand AsyncTask execution briefly : http://codetheory.in/android-asynctask/

Animesh Bhardwaj
  • 709
  • 4
  • 14
  • ????? You did not react on `But I am surprised that AsyncTask can also be executed from the worker thread.`. Nor answered any question. – greenapps Apr 30 '18 at 10:53
0

There is two Threads Main Thread and Worker Thread. Asyntasck works on worker thread.Mostly Asynctask used for background Task.It works on worker thread and publish the result on Main thread.

If Main thread block for 5 sec or more than that Application not responding (ANR) dialogs comes so to avoid this scenario for background task Asynctask used

GParekar
  • 1,209
  • 1
  • 8
  • 15
  • ????? You did not react on `But I am surprised that AsyncTask can also be executed from the worker thread.`. Nor answered any question. – greenapps Apr 30 '18 at 10:53