2016-03-09 45 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我们是否通过编码计算网络延迟?是否有可能由开发商?,请你的答复。在此先感谢 –