我有一个AsyncTask,它将在onCreate
方法中执行。但是,我的ProgressDialog并没有出现。从调试开始,确认正在执行AsyncTask。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifestyle);
context = getApplicationContext();
new testAsync().execute();
}
private class testAsync extends AsyncTask<Void,Void,Void> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this); // tried with context, no difference
pDialog.setTitle("Inserting sample data");
pDialog.setMessage("Please wait. This dialog will be dismissed upon completion.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// TableControllerReadings TCR = new TableControllerReadings(context);
// TCR.insertSampleData(getApplicationContext());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
//delay for 5 seconds
}
}, 5000);
return null;
}
@Override
protected void onPostExecute(Void v) {
pDialog.dismiss();
}
}
答案 0 :(得分:1)
在调用onResume
方法之前,活动不会显示任何视图。如果AsyncTask
执行在onResume
之前完成,那么您将永远不会看到ProgressDialog
。
最好在new testAsync().execute();
onResume
答案 1 :(得分:1)
将pDialog.dismiss();
带入您的计时器帖子。
原因: onPostExecute()
立即致电,因为后台任务已经完成。
它的seprate线程处于延迟状态,因此光标移动到onPostExecute()
private class testAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this); // tried with context, no difference
pDialog.setTitle("Inserting sample data");
pDialog.setMessage("Please wait. This dialog will be dismissed upon completion.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// TableControllerReadings TCR = new TableControllerReadings(context);
// TCR.insertSampleData(getApplicationContext());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
//delay for 5 seconds
pDialog.dismiss();
}
}, 5000);
return null;
}
@Override
protected void onPostExecute(Void v) {
// pDialog.dismiss();
}
}
答案 2 :(得分:0)
在doInBackground中添加pDialog.show();
并在onResume中添加new testAsync().execute();
答案 3 :(得分:0)
您的代码在Thread.sleep(5000)中正常运行;如果你想添加延迟,那么使用Thread.Sleep(/ time in milisec /)而不是Timer.Schedule。由于Timer.Schedule异步任务在显示任何对话框之前执行得如此之快。