0

I am new to multithreading in Android and I have a doubt. I have a AsyncTask instance which I call as BackGroundTask and I start this as:

BackGroundTask bgTask = new BackGroundTask();
bgTask.execute();

However I would like to wait until this call is finished its execution, before proceeding to the other statements of code without blocking UI thread and allowing user to navigate through application.

Please help me so that I can achieve this.

Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
  • "wait until this call is finished" and "without blocking UI thread" is possible only if waiting happens on another thread than UI thread. – Alexei Kaigorodov Mar 13 '14 at 14:00

3 Answers3

0

put your code inside onPostExecute method of AsyncTask, which you wants to execute after work done By worker thread.

Hradesh Kumar
  • 1,765
  • 15
  • 20
0

Try using bgTask.execute().get() this will wait for the background task to finish before moving to the next instruction in the called thread. (Please note that this will block the called thread until background task finishes)

Sojan P R
  • 536
  • 6
  • 9
0

I have found the answer at How do I retrieve the data from AsyncTasks doInBackground()?

And the answer is to use callback as shown below which is copied from above shared link:

The only way to do this is using a CallBack. You can do something like this:

new CallServiceTask(this).execute(request, url);

Then in your CallServiceTask add a local class variable and class a method from that class in your onPostExecute:

private class CallServiceTask extends AsyncTask<Object, Void, Object[]>
{
    RestClient caller;

    CallServiceTask(RestClient caller) {
        this.caller = caller;
    }


    protected Object[] doInBackground(Object... params) 
    {
        HttpUriRequest req = (HttpUriRequest) params[0];
        String url = (String) params[1];
        return executeRequest(req, url);
    }

    protected onPostExecute(Object result) {
        caller.onBackgroundTaskCompleted(result);
    }
}

Then simply use the Object as you like in the onBackgroundTaskCompleted() method in your RestClient class.

A more elegant and extendible solution would be to use interfaces. For an example implementation see this library. I've just started it but it has an example of what you want.

Community
  • 1
  • 1