无法在未调用 Looper.prepare() 的线程内创建处理程序
Can not create handler inside thread that has not called 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();
启动应用程序后。当显示 alertdialog 时,应用程序停止工作。它显示问题:-
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();
我试图在延迟一段时间后显示警告对话框:
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();
启动应用程序后。当显示 alertdialog 时,应用程序停止工作。它显示问题:-
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();