Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing UI task in doinbackground() in Android

Is there a way to do UI task in the doinbackground() of the AsyncTask. I am well aware it is better to do it in onPostExecute method. But in my case since I am need to use a reusable alert, being able to access the UI in my doinbackground would save me a lot of time. That is, I need to tweak the code in 46 places but being able to do this in the doinbackground will need the change in just one place.

Thanks in advance

like image 525
Lincy Avatar asked Apr 02 '13 06:04

Lincy


People also ask

Which method is called by the doInBackground () to publish updates on the user interface thread?

protected final void publishProgress (Progress... This method can be invoked from doInBackground(Params...) to publish updates on the UI thread while the background computation is still running. Each call to this method will trigger the execution of onProgressUpdate(Progress...) on the UI thread.

Which methods are run on the main UI thread AsyncTask?

onPreExecute: This is the first method that runs when an asyncTask is executed. After this, doInBackground is executed. This method runs on the UI thread and is mainly used for instantiating the UI.

Why AsyncTask is used in Android?

Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.


2 Answers

Hope this will solve your problem

    onPreExecute() {
       // some code #1
    }

    doInBackground() {
        runOnUiThread(new Runnable() {
                    public void run() {
                        // some code #3 (Write your code here to run in UI thread)

                    }
                });
    }

    onPostExecute() {
       // some code #3
    }
like image 177
Sreedev Avatar answered Sep 20 '22 05:09

Sreedev


Other than updating UI from onPostExecute(), there are 2 ways to update UI:

  1. From doInBackground() by implementing runOnUiThread()
  2. From onProgressUpdate()

FYI,

onProgressUpdate() - Whenever you want to update anything from doInBackground(), You just need to use publishProgress(Progress...) to publish one or more units of progress, it will ping onProgressUpdate() to update on UI thread.

like image 34
Paresh Mayani Avatar answered Sep 23 '22 05:09

Paresh Mayani