2012-09-11 105 views
1

因此,在我的对话框中,我有一个按钮启动Asynctask下载器从我的服务器获取某个文件;而且工作得很好。但是,我想关闭当前的对话框并在点击按钮上显示ProgressDialog。我将如何处理这个问题?Android对话框和AsyncTask导致UI冻结

目前,如果我点击按钮(我的对话框中的一个元素),整个UI会在下载器从服务器下载文件时冻结。下载程序完成其任务后,进度对话框将显示。

我的代码看起来是这样的

MainActivity{ 

    Dialog dialog; 
    ProgressDialog progress; 

    onCreate(){ 
     dialog = new Dialog(this); 
     progress = new ProgressDialog(this); 
     dialog.setContentView(Some View Resource With My Button); 
     someMethod(); 
     dialog.show(); 
    } 

    someMethod(){ 
     Button button = (Button) dialog.findViewById(resource of button); 
     button.setOnClickListener(new OnClickListener(){ 

      onClick(){ 
       dialog.dismiss(); 
       progress.show(); 
       new DownloaderAsyncTask(progress).execute().get(); 
      } 

        //go to another activity when download finished 

     }); 
    } 

    private class DownloaderAsyncTask extends AsyncTask<Void, Void, Void>{ 

     ProgressDialog progress; 

     DownloaderAsyncTask(ProgressDialog progress){ 
      this.progress = progress; 
     } 

     doInBackGround(){ 
      //Downloading 
     } 

     onPostExecute(){ 
      //Kill connection 
      this.progress.dismiss(); 
     } 

    } 

} 

感谢。请让我知道,如果你们需要任何额外的信息。

+0

显示您的logcat –

+0

没有错误。用户界面被冻结,因为它正在等待下载器完成。下载器完成后,一切正常。但是,我希望当前的对话框被忽略,并且只要单击该按钮,就会显示progressDialog。 – Infinity

+0

不要调用'get()'。看到答案。 –

回答

6
new DownloaderAsyncTask(progress).execute().get(); 

我真的不知道为什么AsyncTaskget()方法 - 它基本上变成异步处理成一个同步,因为它会阻止并等待结果。这就是UI冻结的原因。

如果您想等待下载器完成并执行其他操作,那么这就是onPostExecute(...)的作用。

+0

+1为什么goog会这么做? – o0rebelious0o

2

你的UI线程被冻结,因为你叫get()。不要那样做。相反,启动您AsyncTask,并包含你想在下载结束执行,这样的代码你onPostExecute()调用方法(增加/减少):

someMethod() { 
     Button button = (Button) dialog.findViewById(resource of button); 
     button.setOnClickListener(new OnClickListener(){ 

      onClick(){ 
       dialog.dismiss(); 
       progress.show(); 
       new DownloaderAsyncTask().execute(); 
      } 
     }); 

private void downloaderFinished() { 
    this.progress.dismiss(); 
    /// go to next activity. 
} 

private class DownloaderAsyncTask extends AsyncTask<Void, Void, Void>{ 

     doInBackGround(){ 
      //Downloading 
     } 

     onPostExecute(){ 
      //Kill connection 
      downloaderFinished(); 
     } 
    } 

那怎么应当做到为async代表,好了,异步,因此致电get()杀死所有好处。