2011-04-07 72 views
5

我的AsyncTask阻止了阻止按钮元素,同时下载图像和进度对话框显示延迟 - 它显示一段时间之后图像显示,但下载需要很长时间,并且按钮被阻止(橙色),对话框不显示。AsyncTask阻止UI线程并显示延迟进度条

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的进度条圈 - 对话框仅用于测试,以发现为什么会出现延迟和块。在另一个应用程序中,我使用可运行的线程和元素不被阻塞,但在教程中提到AsyncTask作为更好的解决方案。

+0

这是做正确的方式,检查此链接:http://www.android-ios-tutorials.com/ 182/show-progressbar-while-download-image-using-asynctask-in-android/ – Houcine 2014-09-16 17:25:16

回答

13

图像下载确实在后台线程中执行,但是return task.get();只是等待它完成,这就是阻塞你的主线程。

你应该使用onPostExecute()当任务完成回调,所以不只是关闭该对话框也要做,你需要通过doInBackground()返回的位图什么。

+0

非常感谢您的解释! – Dupla 2011-04-07 21:58:10

+0

感谢您的一天保存提示 – 2013-07-12 15:40:57

2

这是因为你在呼唤AsyncTask#get

如有必要,等待计算完成,然后获取其结果。

您应该执行任何你需要的操作使用图像内onPostExecute()

+0

直接从Android文档中得到的描述可能会更清楚一点,“wait”意味着非常技术性的意义,“调用线程中不会发生任何事情,例如UI更新”。 – 2017-08-11 08:32:43