【问题标题】:Why the dialog don't works in parallel with a thread?为什么对话框不能与线程并行工作?
【发布时间】:2013-09-09 16:46:33
【问题描述】:

为什么对话框不能与线程并行工作? 使用此代码,活动冻结和进度对话框不显示... 我需要在文件下载过程中显示进度对话框...

在onCreate中:

pDialog = new ProgressDialog(this);
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.setTitle(null);
        pDialog.setMessage(getString(R.string.loading));

在下载方式中:

startReader = true;
        pDialog.show();
        new Thread(new Runnable(){
            public void run(){
                for(int i = 1; i <= Integer.parseInt(pages); i++){
                    try{
                        if(!isCached(code,i)){
                            try{
                                CODE TO DOWNLOAD THE FILE;
                                Log.d(TAG, "File downloaded: /"+ code + "/" + "pg" + i + ".rsc");
                            }catch(IOException e){
                                runOnUiThread(new Runnable(){
                                    public void run(){
                                        Toast.makeText(getApplicationContext(), getString(R.string.reader_errinternetcon), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }                       
                    }catch(Exception e){
                        runOnUiThread(new Runnable(){
                            public void run(){
                                Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_SHORT).show();
                            }
                        });
                        startReader = false;
                        break;
                    }
                }
                if(startReader){
                    runOnUiThread(new Runnable(){
                        public void run(){
                            Intent intent = new Intent(MainActivity.this, ReaderActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("Pages", pages);
                            intent.putExtra("Code", code);
                            getApplicationContext().startActivity(intent);
                        }
                    });
                }
            }
        }).start();
        pDialog.dismiss();  

【问题讨论】:

    标签: android multithreading dialog


    【解决方案1】:

    Thread.start() 启动线程但不等待它完成。之后您立即关闭对话。这就是您看不到进度对话框的原因。

    我建议您将后台线程设为AsyncTask。在onPreExecute() 中设置您的进度对话框,在doInBackground() 中进行后台线程处理,并在onPostExecute() 中进行UI 线程后处理,例如关闭进度对话框。

    【讨论】:

    • @FelipePorgeXavier 请支持 laalto 的回答并接受它,这样他就可以因协助您而获得荣誉!
    • ahhh - 很抱歉忘记了这一点......好吧,坚持下去 - @last cnt 你在 11 岁 :))如果你参加,不会花很长时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 2017-01-28
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多