Why Context can't be used in doInBackground() of AsyncTask

前端 未结 3 949
孤街浪徒
孤街浪徒 2021-01-13 12:11

I am just finding what is the fact behind not using Context inside doInBackground(). In-fact we can\'t update the UI inside doInBackground() di

3条回答
  •  借酒劲吻你
    2021-01-13 12:46

    Q Why Context can't be used in doInBackground() of AsyncTask?

    Context as the name suggests, its the context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)

    Where as doInBackground() has no relation/(context) or is not related to the present Activity when its in doInBackground(). You have no access to the main thread. Its completely a new activity which will perform its task even if your Main Thread/Activity has stopped working.

    AsyncTask do not run on the main thread or the main UI thread which you used to call it.It runs on a separate thread to perform the task given to it

    To be able to do changes to the UI after the AsycTask completes, you have to call

      protected void onPostExecute(String string) 
        { 
             Toast c=Toast.makeText(getApplicationContext(), string,  Toast.LENGTH_LONG);
                c.show();
    
              }
    

    All the UI changes can be done in protected void onPostExecute()

    In short doInBackground() Cannot do any changes to your Main Thread and Is not Dependent on your Main UI/Thread so there is no question of using context in doInBackground()

    Q Why we can use context in onPreExecute() and onPostExecute()?

    A AsycTask has

    1.onPreExecute() Pre/Before creating a new Thread (Can do changes to Main Thread )

    onPreExecute() has context to the main thread / AsycTask Still in Main thread

    2.doInBackground() Has created a New thread of its own to perform the task given. Once in this State/Thread You cannot do anything until its complete.

    doInBackground() No Context . New thread is created of its own.Once new thread is created it will complete its given task irrespective of the main thread getting Killed/Stopped./ AsycTask in new thread.

    3.onPostExecute()- After doInBackground() completes its task onPostExecute() is called So that results of the computation can be Used by the main thread

    onPostExecute() has context to the main thread /AsycTask back in Main Thread.

提交回复
热议问题