那麼,請不要問我爲什麼,但我需要啓動一個同步和阻塞活動,以便程序流程在其完成之前不會繼續。我知道如何做一個同步對話框,但我怎麼做一個同步活動?如何進行阻止和同步活動?
以下是兩種方法我試過,但失敗:
// In the 1st activity, start the 2nd activity in the usual way
startActivity(intent);
Looper.loop(); // but pause the program here
// Program continuse running afer Looper.loop() returns
....
// Then, in the second activity's onBackPressed method:
public void onBackPressed() {
// I was hoping the following quit() will terminate the loop() call in
// the first activity. But it caused an exception "Main thread not allowed
// to quit." Understandable.
new Hanlder().getLooper().quit();
}
我還試圖用另一個線程來實現這一目標:
// In the first activity, start a thread
SecondThread m2ndThread = new SecondThread(this);
Thread th = new Thread(m2ndThread, "Second Thread");
th.run();
synchronized(m2ndThread) {
m2ndThread.wait();
}
class SecondThread implements Runnable {
Activity m1stActivity;
SecondThread(Activity a) {
m1stActivity = a;
}
public void run() {
Looper.prepare();
Handler h = new Handler() {
public void handleMessage() {
Intent intent = new Intent(m1stActivity, SecondActivity.class);
m1stActivity.startActivity(intent); // !!!!!!!!!!!!!!
}
}
h.sendEmptyMessage(10); // let it run
Looper.quit();
}
}
然而,這種方法是行不通的,因爲當我m使用第一個活動來啓動第二個活動,主線程已處於等待狀態並且什麼都不做。所以第二項活動甚至沒有創建。 (這很具有諷刺意味:你必須使用一項活動來開始一項活動,但是當它已經處於等待狀態時你怎麼能這樣做?)
你不能只顯示一個ProgressDialog?這將阻止用戶在執行您正在執行的任何任務時能夠與您的活動進行交互。 – dmon 2011-04-30 18:14:47
@dmon,嗯......,是ProgressDialog阻止?嗯...有趣。我肯定會試一試。非常感謝。 – wwyt 2011-04-30 18:40:53
我的意思是它不會阻止主線程執行,顯然,但你可以在後臺執行你的工作,而用戶留在那裏盯着真棒棘手thinghy。 – dmon 2011-04-30 18:42:55