如何在等待线程完成时显示“进度”对话框?

时间:2012-06-07 10:55:59

标签: android

以下是我试图在onCreate()

内调用的代码
        _t = new TheThread(this);
        pd = new ProgressDialog(this);
        pd.setMessage("Trip Detection ..");
        pd.show();
        _t.start();
        while(_t.isAlive()){
            //DO NOTHING..WIAITING TILL MAIN THREAD FISHIN
        }
        printToScreen();
        pd.dismiss();          

printToScreen()更新列表视图。使用tread _t更新列表视图的内容。但是,当我称这种方法时,我看不到任何“等待”的消息。电话冻结像以前一样(当我没有在线程上运行内容时)。有什么建议吗?

4 个答案:

答案 0 :(得分:1)

使用AsyncTask

private class DownloadingProgressTask extends
        AsyncTask<String, Void, Boolean> {

    private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);

    /** progress dialog to show user that the backup is processing. */

    /** application context. */

    protected void onPreExecute() {
         this.dialog.setMessage("Please wait");
         this.dialog.show();
    }

    protected Boolean doInBackground(final String... args) {
        try {
            downloadFile(b.getString("URL"));
            return true;
        } catch (Exception e) {
            Log.e("tag", "error", e);
            return false;
        }
    }

    @Override
    protected void onPostExecute(final Boolean success) {

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        if (success) {
            Toast.makeText(ShowDescription.this,
                    "File successfully downloaded", Toast.LENGTH_LONG)
                    .show();
            imgDownload.setVisibility(8);
        } else {
            Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
                    .show();
        }
    }

答案 1 :(得分:1)

以下代码段将为您提供帮助。

progressDialog.show();

    new Thread()
      {
        public void run()
         {
             //do async operations here

             handler.sendEmptyMessage(0);
         } 
      }.start();

    Handler handler = new Handler()
            {

                @Override
                public void handleMessage(Message msg)
                {
                    progressDialog.dismiss();
                    super.handleMessage(msg);
                }

            };

答案 2 :(得分:0)

class doback extends AsyncTask < URL, Integer, Long > {

    protected Long doInBackground(URL...arg0) {
        try {

        } catch (Exception e) {

        }
        return null;
    }

    protected void onProgressUpdate(Integer...progress) {

    }

    protected void onPostExecute(Long result) {
        try {
            dialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
            dialog.dismiss();
        }
    }

}

答案 3 :(得分:0)

按如下所示创建对话框

pd = ProgressDialog.show(this, "Loading..", "Please Wait..", true,false);
new Thread(new Runnable() {                 
            @Override
            public void run() { 
                                               // your code here
                    }
        }).start();