Android Dialog和AsyncTask导致UI冻结

Inf*_*ity 1 java multithreading android android-ui android-asynctask

所以,在我的Dialog中,我有一个启动Asynctask下载器的按钮,从我的服务器获取一些文件; 这工作得很好.但是,我想解除当前的Dialog并显示单击按钮上的ProgressDialog.我该如何处理这个问题?

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

我的代码看起来像这样

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();
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

谢谢.如果您需要任何其他信息,请告诉我.

Squ*_*onk 6

new DownloaderAsyncTask(progress).execute().get();
Run Code Online (Sandbox Code Playgroud)

我真的不知道为什么AsyncTask有这个get()方法 - 它基本上把异步进程变成了同步进程,因为它会阻塞并等待结果.这就是用户界面冻结的原因.

如果你想等待下载器完成然后做其他事情,那onPostExecute(...)就是为了什么.