UI延迟显示asynctask

时间:2013-05-21 14:54:16

标签: android android-asynctask

我在按钮的onclicklistener中定义了一个AsyncTask,一旦用户单击该按钮,理想情况下在asynctask下载时会显示进度对话框。

但是,进度对话框只是闪烁并在结果返回之前消失,并且当asynctask在后台运行时按钮会聚焦。

有人可以帮我弄清楚我在这里做错了什么吗?代码段:

    final ProgressDialog progressDialog = new ProgressDialog(context);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

    ((Button)findViewById(R.id.buttonLoginActivity)).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            AsyncTask<Void, Void, Void> downloadTask= new AsyncTask<Void, Void, Void>(){
                @Override
                protected Void doInBackground(Void... params) {
                    String data = Service.getSomeData();
                            context.getContentResolver.notifyChange("content://some_url");
                        return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    if(progressDialog== null) return;
                    if(progressDialog!=null) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }
                }
            };

            progressDialog.show();

            downloadTask.execute();
            try{
                downloadTask.get();
            }catch(Exception e){
                e.printStackTrace();
                return;
            }
        }
    });

2 个答案:

答案 0 :(得分:1)

请勿使用get()

downloadTask.get();

这是一个阻止通话。来自Docs

  

如果需要等待计算完成,然后检索其结果。

只需使用execute(),然后根据onPostExecute()

中的结果执行您所需的操作

答案 1 :(得分:0)

显示需要编写的onPreExecute上的进度对话框,它将在UI线程上运行,而不是在后台运行(android 4)

我也会在new Handler().post(myAsynctaskcaller)

上调用异步任务
@Override
protected void onPreExecute() {
       super.onPreExecute();
       progressDialog.show();
}