繁体   English   中英

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

[英]How can I show a Dialog box from a thread other than the UI thread

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

public void showWaitDialog() {

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


}

您可以:

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

  • 在您的Activity定义一个BroadcastReceiver ,然后从您的线程中通过Bundle发送一个包含必要信息的Intent

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

  • 使用runOnUiThread

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

为什么不使用AsyncTask 您可以在onPreExecute()上告诉Task显示“请稍候”对话框,然后在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 ,第二个值传递给进度值,第三个值是从doInBackgroundonPostExecute的返回值。

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

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上的更新视图,请参见非活动类中的display progressdialog带有runOnUiThread的Loading对话框 希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM