簡體   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