Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask block UI thread and show progressbar with delay

My AsyncTask is blocking block button element while downloading image and progress dialog is shown with delay - its shows for a while before image is shown, but downloading takes long time and button is blocked (orange) and dialog is not shown.

 public  Bitmap download(String url, ProgressBar progressbar) throws InterruptedException, ExecutionException {
     BitmapDownloaderTask task = new BitmapDownloaderTask(progressbar);
     task.execute(url);
     return task.get();
}

class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {



    public BitmapDownloaderTask(ProgressBar progressbar) {

    }
    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(ShowActivity.this);
        dialog.setMessage("Loading");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    protected Bitmap doInBackground(String... Params) {
        return imageLoader.getBitmap(params[0]);

    }
    @Override
    protected void onPostExecute(Bitmap bitmap) {
         dialog.dismiss();


    }
}    

In button listener, simply call download function, the progress parameter is because I have progress bar circle in imageview - the dialog is for testing only, to found why is there the delay and block. In another app I use runable and thread and element is not blocked, but in tutorials is AsyncTask mentioned as better solution for this.

like image 393
Dupla Avatar asked Apr 07 '11 14:04

Dupla


2 Answers

The image download is indeed executed in the background thread, but with return task.get(); you're just waiting for it to finish, and that's what's blocking your main thread.

You should use onPostExecute() as a callback for when the task has finished, so not just to dismiss the dialog but also to do what you need with the bitmap returned by doInBackground().

like image 87
bigstones Avatar answered Sep 18 '22 16:09

bigstones


It is because you are calling AsyncTask#get:

Waits if necessary for the computation to complete, and then retrieves its result.

You should perform whatever operation you need to use the image for within onPostExecute()

like image 30
dave.c Avatar answered Sep 20 '22 16:09

dave.c