我正在运行进程时使用ProgressDialog遇到问题。我已经尝试了所有不正确的方法,并查看了许多网站,提供了我想要做的例子但是,我仍然遇到线程在ProgressDialog出现之前运行的问题。以下是我最近的尝试:
new Thread(new Runnable() {
public void run() {
dialog = new ProgressDialog(EPD.this);
dialog.setMessage("Loading. Please Wait...");
dialog.show();
}
}).run();
getMostWanted();
除了尝试这种方式之外,我还尝试在getMostWanted()中使用新的Thread但是我仍然有相同的结果。它在getMostWanted()和没有对话框时暂停约4或5秒。
提前感谢您的帮助。
答案 0 :(得分:2)
如果您在主线程上,则应使用它来显示ProgressDialog并为getMostWanted()
分离另一个线程。假设您希望结束getMostWanted()
以关闭对话框,您应该查看AsyncTask:
private class GetMostWanted extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog;
public GetMostWanted() {
dialog = new ProgressDialog(EPD.this);
dialog.setMessage("Loading. Please Wait...");
}
protected void onPreExecute() {
dialog.show();
}
protected void doInBackground(Void... unused) {
getMostWanted();
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
这样你的处理就在doInBackground()
的后台线程上执行,然后在你完成之后,你可以在onPostExecute()
的主线程上关闭对话框。
现在你可以使用:
new GetMostWanted(dialog).execute();
答案 1 :(得分:1)
@Amin是正确的,解决问题的一个好方法是使用AsyncTask
,尽管他的实现并不完全符合您的需求。您可以在onPreExecute()
中创建对话框,然后在onPostExecute()
中将其删除。
您遇到的问题是创建一个新的Thread
然后调用run
将在UI线程上运行您的线程。您对getMostWanted()
的调用也会在UI线程中执行,并阻止创建对话框。
因此,您可以选择使用其他人建议的AsyncTask
,或使用Thread
和Handler
,Handler
执行UI更新。
答案 2 :(得分:0)
无法保证线程的执行时间。我建议你改用AsycTask。这是一个例子。然后,您可以执行它并更新您的进度条。
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
答案 3 :(得分:0)
Jay ...如果你想使用线程和处理程序。将时间密集型任务放入可运行的方法中。创建“包含”可运行对象的线程并调用线程启动,以便在单独的线程上运行时间密集型任务。您应该能够在UI线程中启动对话框。当后台线程完成并通知处理程序时,您应该能够解除绑定到UI线程的处理程序中的对话框。这是使用线程的一些代码。此代码段在新线程中启动了一个耗时的过程。
buttonConfuseText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String inString= editTextPlainText.getText().toString();
Thread thread= new Thread( new Runnable() {
public void run() {
String outString= encrypt(password,inString); //<== time intensive task here
Message msg= Message.obtain();
Bundle b= new Bundle();
b.putString("encryptedText",outString);
msg.setData(b);
handler.sendMessage(msg);
Log.d(TAG,outString);
}
});
thread.setDaemon(true);
thread.start();
}
});
你等待线程在这里完成:
public class ConfuseText extends Activity {
private Handler handler= new Handler(){
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
ConfuseText.this.onThreadMessage(msg); //<== close dialog here if you wish
}
};
public void onThreadMessage(Message msg){
Bundle b= msg.getData();
String encryptedText="";
if (b != null){
encryptedText= b.getString("encryptedText");
}
Log.d(TAG,encryptedText);
}