2013-07-22 81 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

相關問題