无法在未调用 Looper.prepare() 的线程中创建处理程序



我试图在一段时间延迟后显示警报对话框:

Thread thread = new Thread() {
@Override
public void run() {
try {
synchronized (this) {
wait(3000);
}
} catch (InterruptedException ex) {
}
final AlertDialog.Builder builder = new AlertDialog.Builder(stop_watch.fa);
builder.setMessage("Want to exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
locator_activity.fa.finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
};
thread.start();

启动应用程序后。当需要显示警报对话框时,应用程序停止工作。它显示了问题:-

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

AlertDialogs 是 UI 元素,因此需要在 UI 线程上执行工作:

new Thread() {
public void run() {
activity.this.runOnUiThread(new Runnable() {
public void run() {
// Show dialog..
}
});
}
}.start();

最新更新