我正在尝试阻塞主线程,并向用户显示一个对话框活动(在另一个android:process
中运行),以进行是/否决定。用户单击“是”或“否”后,对话框活动结束,主线程恢复。请注意,对于我的项目,必需阻止主线程。
启动对话框:
private boolean getUserDecision() {
DialogRunnable dialogRunnable = new DialogRunnable();
Thread thread = new Thread(dialogRunnable);
thread.start();
while (thread.isAlive()) {
try {
// block the thread until user enters his decision
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return dialogRunnable.decision;
}
还有DialogRunnable
:
class DialogRunnable extends Runnable {
public boolean decision;
@Override
public void run() {
Looper.prepare();
Intent intent = /* intent for launching the dialog */
intent.setResultMessenger(new Messenger(new Handler() {
@Override
public void handleMessage(Message msg) {
Looper.myLooper().quit();
decision = msg.arg1 == 1;
}
}));
startActivity(intent);
Looper.loop();
}
}
如果在主线程上调用getUserDecision
,则对话框在明显的延迟(〜1s)后启动,但是从后台线程调用该方法将立即启动对话框。为什么?