我有一个Android应用程序,我正在执行以下操作:
private void onCreate() {
final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true);
new Thread() {
public void run() {
//do some serious stuff...
dialog.dismiss();
}
}.start();
stepTwo();
}
我想确保我的线程在stepTwo()之前完成;叫做。我怎么能这样做?
谢谢!
答案 0 :(得分:3)
Thread实例有一个join方法,所以:
private void onCreate() {
final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true);
Thread t = new Thread() {
public void run() {
//do some serious stuff...
dialog.dismiss();
}
};
t.start();
t.join();
stepTwo();
}
你可能想试试这个:
private void onCreate() {
final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true);
Thread t = new Thread() {
public void run() {
//do some serious stuff...
SwingUtilities,invokeLater(new Runnable() {
public void run() {
dialog.dismiss();
}
});
stepTwo();
}
};
t.start();
}
因为onCreate在UI线程中,所以在那里加入会冻结UI直到onCreate完成之后,保存任何对话框直到那时。 stepTwo
必须使用SwingUtilities.invokeLater
来自行更改UI。
答案 1 :(得分:2)
如果你想在后台运行,我建议使用the AsyncTask
class,这样做可以确保你正确地与UI线程进行交互。
此外,如果您希望在后台任务完成后运行代码,则可以调用该方法。没有理由在onCreate()
内等待。
您的代码将如下所示:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MyActivity.this, "Please wait..", "Doing stuff..", true);
}
@Override
protected Void doInBackground(Void... params) {
//do some serious stuff...
return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
stepTwo();
}
}
答案 2 :(得分:1)
另一个选择是简单地将step2()
移动到线程中,以便在线程任务完成后执行:
private void onCreate() {
final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true);
new Thread() {
public void run() {
//do some serious stuff...
dialog.dismiss();
stepTwo();
}
}.start();
}