Waiting Till the Async Task Finish Its Work

Waiting till the async task finish its work

wait until this call is finish its executing

You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.

To get result back in UI Thread start AsyncTask as :

String str_result= new RunInBackGround().execute().get();

Android: how to wait AsyncTask to finish in MainThread?

class OpenWorkTask extends AsyncTask {

@Override
protected Boolean doInBackground(String... params) {
// do something
return true;
}

@Override
protected void onPostExecute(Boolean result) {
// The results of the above method
// Processing the results here
myHandler.sendEmptyMessage(0);
}

}

Handler myHandler = new Handler() {

@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
// calling to this function from other pleaces
// The notice call method of doing things
break;
default:
break;
}
}
};

Android AsyncTask wait until finished

Use the getStatus() method.

while (task.getStatus() != Status.FINISHED);

A better way to do this would be to call split() inside the onPostExecute() method, since onPostExecute() runs on the UI thread anyway and the while() call would block the current thread it's running in.

Waiting for ASyncTask to finish or variable to be set

Just put your code which you want to execute after the Variable is changed in a function and call this function from onPostExecute.

Android wait AsyncTask to finish

You have two options:

Either use the AsyncTask's method get(long timeout, TimeUnit unit) like that:

task.get(1000, TimeUnit.MILLISECONDS);

This will make your main thread wait for the result of the AsyncTask at most 1000 milliseconds (as per @user1028741 comment: actually there is also infinetly waiting method - AsyncTask#get() which might also do the work for you in some cases).

Alternatively you can show a progress dialog in the async task until it finishes. See this thread (No need for me to copy past the code). Basically a progress dialog is shown while the async task runs and is hidden when it finishes.

You have even third option:" if Thread is sufficient for your needs you can just use its join method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.



Related Topics



Leave a reply



Submit