2

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

public void showWaitDialog() {

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


}
4

3 回答 3

6

你可以:

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

  • BroadcastReceiver在您的线程中定义一个Activity并从您的线程中发送一个Intent带有必要信息的Bundle

  • 使用AsyncTask和方法publishProgress(),onProgressUpdate()onPostExecute()通知Activity进度或任务何时完成

  • 使用runOnUiThread.

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

于 2013-07-22T23:00:17.293 回答
2

为什么不使用AsyncTask. 您可以告诉 Task ononPreExecute()以显示“请稍候”对话框,然后onPostExecute(Result result)您可以删除该对话框。这两种方法doInBackground(Params... params)在后台线程中发生时在 UI 线程上工作。

例子:

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,第二个值是进度值,第三个值是来自doInBackgroundto的返回值onPostExecute

于 2013-07-22T22:56:45.740 回答
2

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

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

        }
    });

有关 Android 上的更新视图,请参阅非活动类中的显示进度对话框和使用 runOnUiThread 加载对话框。希望这可以帮助。

于 2013-07-22T22:57:52.507 回答