2013-07-22 76 views
0

我的应用程序需要读取gps,因此在主线程中,我启动了一个读取GPS的线程,但我无法显示一个对话框,显示“Please等待”。我也使用Handler绑定,但这也不起作用。什么是最好的控制从第二线程的“请稍候”对话框?谢谢!如何从UI线程以外的线程显示对话框

public void showWaitDialog() { 

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


} 

回答

2

为什么不使用AsyncTask。您可以通过onPreExecute()告诉Task显示Please wait对话框,然后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

正如其他答案已正确建议,您可以优先使用AsyncTask。以下是如何将其用于您的目的的示例:AsyncTask Android example。否则,您也可以使用runOnUiThread方法。从第二个线程中进行UI线程的更改(例如:对话框和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。 希望这有助于。

4

您可以:

  • 定义你的UI线程的Handler(例如,在Activity),然后把它传递给你的线程。现在从您调用handler.post(runnable)的线程排列要在UIThread上执行的代码。

  • 定义您Activity一个BroadcastReceiver和你线程与在Bundle

  • 使用必要的信息发送IntentAsyncTask和方法publishProgress()onProgressUpdate()onPostExecute()告知进度的Activity或当taask完成时

  • 使用runOnUiThread

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

+0

您好我试图通过该处理程序改变 '螺纹MyThread的=新MyClass的();' 到 '螺纹MyThread的=新MyClass的(处理程序);' 然后在接收它的run()方法,改变它到 '跑(处理程序处理程序);' 但是这并没有工作,什么是正确的方法来做到这一点? 谢谢 – user2566468

+0

你有没有调用handler.post(runnable)?您可以编辑您的帖子,并在代码无法正常工作的情况下使用代码进行更新。 –

+0

是的,我做了,它的工作,但我没有通过处理程序,我只是把它公开在Activity类,然后用它从Thread类调用它Activity.handler,但我的问题是如何传递处理程序作为论据。谢谢! – user2566468

相关问题