2016-03-09 46 views
1

在異步任務中運行時,我必須顯示不同的消息進行中的對話框。如何在asyncTask中顯示不同的消息進度條

首先,我需要顯示消息「請稍等」,然後「從服務器下載」,然後「請稍等」。

我嘗試過publishProgress,但是當我運行應用程序時,在我的ProgressDialog上,只顯示最後一條消息「Please wait for sometime」。我如何顯示這三條消息?

private class Sample extends AsyncTask<String, String, String> { 
    ProgressDialog testdialog; 

    @Override 
    protected void onPreExecute() { 
     testdialog = new ProgressDialog(test.this); 
     testdialog.setTitle("Title"); 
     testdialog.setMessage("Please wait "); 
     testdialog.setIndeterminate(false); 
     testdialog.setCancelable(false); 
     testdialog.setCanceledOnTouchOutside(false); 
     testdialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... urls) { 
     publishProgress("Downloading from server"); 
     publishProgress("Please wait for sometime"); 
     /* here I code the background downloading process*/ 
    } 

    @Override 
    protected void onProgressUpdate(String... pro) { 
     testdialog.setMessage(pro[0]); 
     testdialog.setMessage(pro[1]); 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     testdialog.dismiss(); 
    } 
} 
+0

它發生得非常快,你沒有注意到,所以最後一條消息只出現,tyr在'publishProgress()'的2次調用之間增加一些延遲(睡眠),如2秒,你應該注意到progressDialog上的2條消息 – Yazan

+0

@ Gokul Rajkumar **嘗試這些鏈接都在同一線程** http://stackoverflow.com/questions/7970113/change-a-dialogs-message-while-using-asynctask **還** http:// stackoverflow。 com/questions/23961605/android-progress-dialog-publishprogress-method –

+0

@Yazan感謝你的回覆,當我試着爲每個publishProgress添加延遲屏幕變爲空白時,你可以給出一些更好的答案或任何示例顯示進度對話中的不同消息。 –

回答

2

試試這個代碼doInBackground()它應該除了最後一個延遲2秒鐘每個 顯示所有郵件將保持對話,直到對話框關閉或隱藏

@Override 
protected String doInBackground(String... urls) { 
    try {//this should let "Please wait " appears for 2 secs 
     Thread.sleep(2000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    publishProgress("Downloading from server"); 

    try {////this should let "Downloading from server" appears for 2 secs 
     Thread.sleep(2000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 

    publishProgress("Please wait for sometime"); 

    try {////this should let "Please wait for sometime" appears for 2 secs 
     Thread.sleep(2000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    /* here i code the background downloading process*/ 
} 

也爲onProgressUpdate()方法準備接收多參數,但你只發送一個,所以不需要使用pro [1],刪除第二個setMessage()致電

@Override 
protected void onProgressUpdate(String... pro) { 
    testdialog.setMessage(pro[0]); 
} 
+0

謝謝yazan,代碼工作正常 –

+0

@Yazan感謝您的回答,它的工作... –

+0

@Yazan我們是否通過編碼計算網絡延遲?是否有可能由開發商?,請你的答覆。在此先感謝 –