当AsyncTask.get()称为ProgressDialog未显示 [英] ProgressDialog not shown when AsyncTask.get() called

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

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/5583137/asynctask-block-ui-threat-and-show-progressbar-with-delay">AsyncTask阻止用户界面的威胁,并显示进度延迟

我想显示progressDialog,而从任何服务器检索的JSON。所以,我用的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的实例,直到我打电话获得()方法。我想这是阻塞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();
    }
}

这里是myActivity这是调用AsyncTask的:

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两者是没有问题的。但是,如果我想获得与获得()的结果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)

这是什么问题?

推荐答案

的get() 等待如有必要,计算完成,然后获取其结果。这意味着,你挡你的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天全站免登陆