AsyncTask 阻塞 UI 线程并延迟显示进度条 [英] AsyncTask block UI thread and show progressbar with delay
问题描述
我的 AsyncTask 在下载图像时阻止块按钮元素,并且进度对话框延迟显示 - 它在显示图像之前显示了一段时间,但下载需要很长时间并且按钮被阻止(橙色)并且没有显示对话框.
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();
}
}
在按钮侦听器中,只需调用下载函数,进度参数是因为我在imageview中有进度条圆圈-对话框仅用于测试,以找出延迟和阻塞的原因.在另一个应用中,我使用了 runable 并且线程和元素没有被阻塞,但在教程中提到 AsyncTask 是更好的解决方案.
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.
推荐答案
图片下载确实是在后台线程执行的,但是用 return task.get();
你只是在等待它完成,这就是阻塞你的主线程.
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.
您应该使用 onPostExecute()
作为任务完成时的回调,这样不仅可以关闭对话框,还可以对 doInBackground() 返回的位图执行您需要的操作)
.
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()
.
这篇关于AsyncTask 阻塞 UI 线程并延迟显示进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!