我使用以下代码创建了一个 AsyncTask 类
public class removeDialog extends AsyncTask<Void, Void, Void> {
Context c;
ProgressDialog asyncDialog;
String page;
public removeDialog(Context c, String page) {
this.c = c;
this.page = page;
asyncDialog = new ProgressDialog(c);
}
@Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
if (page == "algemeneVoorwaarden") {
Intent intent = new Intent(c, algemeneVoorwaarden.class);
c.startActivity(intent);
}
if (page == "contact") {
Intent intent = new Intent(c, contactTest.class);
c.startActivity(intent);
}
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
//don't touch dialog here it'll break the application
//do some lengthy stuff like calling login webservice
return null;
}
@Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}
我第一次尝试: 第一次看到 ProgressDialog 时,但第二次我想打开该 Activity 时,我什么也没得到。
我第二次尝试: 即使是第一次尝试,我也没有得到任何 ProgressDialog。
我在 AsyncTask 类中执行我的代码,代码:
voorwaarden.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new removeDialog(c, "algemeneVoorwaarden").execute();
}
});
有人知道为什么它不起作用吗?请帮助我。
最佳答案
您的对话框将在显示后立即关闭,因为您的 doInBackground
为空。尝试添加一个 Thread.sleep() 几秒钟,只是为了模拟延迟。
此外,我怀疑您正在开始的新 Activity 会将您的对话抛在后面。因此,我建议您暂时在没有这些新 Activity 的情况下测试代码。
public class RemoveDialog extends AsyncTask<Void, Void, Void> {
ProgressDialog asyncDialog;
public RemoveDialog(Context c) {
asyncDialog = new ProgressDialog(c);
}
@Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(3000);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}
关于java - ProgressDialog 新 Activity Asynctask 未显示,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40652699/