AsyncTask的方块UI线程,并显示进度延迟 [英] AsyncTask block UI thread and show progressbar with delay

查看:81
本文介绍了AsyncTask的方块UI线程,并显示进度延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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 - 对话框仅用于测试,以发现为什么会出现延迟和块。在另一个应用程序,我使用的可运行和线程和元素没有被阻塞,但在教程中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.

推荐答案

图片下载确实执行在后台线程,但返回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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆