调用 AsyncTask.get() 时未显示 ProgressDialog [英] ProgressDialog not shown when AsyncTask.get() called

查看:12
本文介绍了调用 AsyncTask.get() 时未显示 ProgressDialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
AsyncTask 阻止 UI 威胁并延迟显示进度条

我想在从任何服务器检索 JSON 时显示一个 progressDialog.所以我使用 AsyncTask 作为解决方案(不确定有什么不同的出路).

I want to show a progressDialog while retrieving JSON from any server. So I had used AsyncTask as a solution (not sure any different way out).

一切都很好,ProgressDialog 可以正常工作,直到我使用 AsyncTask 实例调用 .get() 方法.我想它以某种方式阻止了 UI.这是我的 AsyncTask:

Everything is fine, the ProgressDialog works properly until I call .get() method using AsyncTask instance. I suppose it's blocking UI somehow. Here is my AsyncTask:

public class myAsync extends AsyncTask<String, String, List> {

    String message; // for dialog message
    ProgressDialog progress; 
    Intent myIntent;
    Context ctx;

    public myAsync(String message, Context ctx) {
        this.message = message;
        this.ctx = ctx;
        progress = new ProgressDialog(ctx);
    }

    @Override
    protected void onPreExecute() { 
        progress.setMessage(message);
        progress.setIndeterminate(true);
        progress.setCancelable(false);
        progress.show();    
    }

    @Override
    protected List doInBackground(String... params) {
        //returns any list after the task
        return anyList; 
    }

    @Override
    protected void onPostExecute(List result) {
        if(progress.isShowing())
            progress.dismiss();
    }
}

这里是调用 AsyncTask 的 myActivity:

And here is myActivity which is calls AsyncTask:

myAsync asyncTask = new myAsync("Loading...", this);
asyncTask.execute("Any string", "Other string");
asyncTask.get(); // If I comment out this line, ProgressDialog works

执行后,当我尝试从 doInBackground 和 onPostExecute 记录结果时,没有问题.但是如果我想使用 .get() 结果 ProgressDialog 没有显示或显示的时间太短(可能是 0.2 秒)

After execute, when I tried to log the result from doInBackground and onPostExecute both there is no problem. But if I want to get with .get() the result ProgressDialog is not shown or shown so little time (maybe 0.2 seconds)

有什么问题吗?

推荐答案

Yes, get() waits 如果需要计算完成,然后检索其结果.这意味着,您正在阻塞 UI 线程,等待结果.

Yes, get() waits if necessary for the computation to complete, and then retrieves its result. This means, that you are blocking your UI thread, waiting for the result.

解决方案:不要调用get

通常,您会在 postExecute 中调用一个函数(回调).

Usually, you will call a function (callback) in the postExecute.

这篇关于调用 AsyncTask.get() 时未显示 ProgressDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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