我正在android中创建一个耗时的操作线程。我希望主屏幕显示一个进度对话框,其中包含一条消息,告知操作正在进行中,但是我想在线程完成后关闭该对话框。我已尝试使用join但它会锁定线程并且不显示对话框。我尝试使用:
dialog.show();
mythread.start();
dialog.dismiss();
但是对话框没有显示。如何创建该序列但是等待线程结束而不锁定主线程?
据我所知:
public class syncDataElcanPos extends AsyncTask<String, Integer, Void> {
ProgressDialog pDialog;
Context cont;
public syncDataElcanPos(Context ctx) {
cont=ctx;
}
protected void onPreExecute() {
pDialog = ProgressDialog.show(cont,cont.getString(R.string.sync), cont.getString(R.string.sync_complete), true);
}
protected Void doInBackground(String... parts) {
// blablabla...
return null;
}
protected void onProgressUpdate(Integer... item) {
pDialog.setProgress(item[0]); // just for possible bar in a future.
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
但是当我尝试执行它时,它给了我一个例外:“无法添加窗口”。
答案 0 :(得分:3)
完成线程后,使用runOnUIThread方法关闭对话框。
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
答案 1 :(得分:1)
要做到这一点有两种方法,(我更喜欢第一个第二个:AsyncTask):
首先:您显示alertDialog
,然后显示方法run()
,您应该这样做
@override
public void run(){
//the code of your method run
//....
.
.
.
//at the end of your method run() , dismiss the dialog
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
第二:使用像这样的AsyncTask:
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
//create and display your alert here
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Downloading data ...", true);
}
protected Void doInBackground(Void... unused) {
// here is the thread's work ( what is on your method run()
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
//dismiss the alert here where the thread has finished his work
pDialog.dismiss();
}
}
答案 2 :(得分:0)
在{posblexecute中的AsyncTask中你可以调用dismiss
这是来自其他线程的示例
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true);
}
protected Void doInBackground(Void... unused) {
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}