Android : Calling the methods on UI thread from AsyncTask doInBackground method

前端 未结 4 1801
小鲜肉
小鲜肉 2020-12-03 05:30

I am using AsyncTask to upload data to UI. i wrote the code to download data from server in a separate method and i am calling that method from doinBackground. It will give

相关标签:
4条回答
  • 2020-12-03 05:56

    Use doInBackground() just for tasks that :

    1. Take some time
    2. Are not UI related

    Then you can implement AsyncTask.onPostExecute() to run code to handle those results on main UI thread from AsyncTask

    From JavaDoc for AsyncTask.onPostExecute():

    "Runs on the UI thread after doInBackground. ... "

    0 讨论(0)
  • 2020-12-03 06:06

    any alternative process is there to access the UI method from doinBackground.?

    Call publishProgress() in doInBackground(). Put your UI-updating logic in onProgressUpdate() of your AsyncTask. onProgressUpdate() will be called on the main application thread (a.k.a., UI thread) after you call publishProgress(). Here is a sample project demonstrating this.

    0 讨论(0)
  • 2020-12-03 06:11

    As the others have pointed out, you can use runOnUiThread. But, it seems a little odd that you would want to do that in your doInBackground. If you are wanting to indicate progress to the user you would want to handle that in AsyncTask.onProgressUpdate and call publishProgress in your doInBackground.

    You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html

    -Dan

    0 讨论(0)
  • 2020-12-03 06:15

    Call runOnUiThread(Runnable action)

    more here

    0 讨论(0)
提交回复
热议问题