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.
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()
.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With