如何从UI线程以外的线程显示对话框

时间:2013-07-22 22:52:17

标签: java android

我的应用程序需要gps阅读,所以在主线程上我启动了一个读取GPS的线程,但是我无法显示一个“请稍候”的对话框。我也使用Handler绑定,但这也不起作用。从第二个线程控制“请稍候”对话框的最佳方法是什么?谢谢!

public void showWaitDialog() {

    prgDialog = new ProgressDialog(context);
    prgDialog.setTitle("Please wait.");
    prgDialog.setMessage("Please wait.");
    prgDialog.setCancelable(false);
    prgDialog.show();


}

3 个答案:

答案 0 :(得分:5)

你可以:

  • 在您的UI线程中定义Handler(例如在Activity中),然后将其传递给您的主题。现在从线程中调用handler.post(runnable)来排队要在UIThread上执行的代码。

  • BroadcastReceiver中定义一个Activity,然后通过线程发送一个Intent,其中包含Bundle

  • 中的必要信息
  • 使用AsyncTask和方法publishProgress(),onProgressUpdate()onPostExecute()通知Activity进度或任务时间已完成

  • 使用runOnUiThread

这取决于您的需求。对于短期运行的异步操作,AsyncTask是一个不错的选择。

答案 1 :(得分:2)

为什么不使用AsyncTask。您可以告诉onPreExecute()上的任务显示请等待对话框,然后onPostExecute(Result result)您可以删除对话框。这两个方法正在处理UI线程,而doInBackground(Params... params)正在后台线程中发生。

示例:

private class GetGPSTask extends AsyncTask<null, null, null>{

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
                    showWaitDialog();  <-Show your dialog
    }


    @Override
    protected void doInBackground(null) {

                //your code to get your GPS Data
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
                    HideDialogbox(); <-Code to hide the dialog box
    }
}

请记住在需要时更改模板类型。在说AsynTask时,第一个值传递给doInBackground,第二个值传递给进度值,第三个值是从doInBackgroundonPostExecute的返回值。

答案 2 :(得分:2)

正如其他答案正确建议的那样,您最好使用AsyncTask。以下是如何将其用于您的目的的示例:AsyncTask Android example。否则,您也可以使用runOnUiThread方法。从第二个线程内部对UI线程进行更改(例如:Dialogs和Toasts)。根据其documentation,它说:

It runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

例如;

Your_Activity_Name.this.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            // your stuff to update the UI
            showWaitDialog();

        }
    });

请参阅display progressdialog in non-activity classLoading Dialog with runOnUiThread for update view on Android。 希望这可以帮助。

相关问题