【问题标题】:alert dialog inside asynctask in androidandroid中asynctask内的警报对话框
【发布时间】:2011-08-24 19:28:57
【问题描述】:
我需要在Asynctaskin android 中显示Alertdialog,但它不会在 throws 异常中显示。
05-13 14:59:35.522: WARN/System.err(1179): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
谢谢。
【问题讨论】:
标签:
android
android-layout
【解决方案1】:
无法从后台线程操作 UI。为此,请使用处理程序或 AsyncTask 的 onPre/Post 方法。
【解决方案2】:
在 onPostExecute() 方法而不是 doInBackground 中显示对话框。
希望有帮助
【解决方案3】:
我认为this 可能是您的问题——您无法从 doInBackground 内部显示对话框。
【解决方案4】:
从后台线程到达 UI 线程没有问题(更清楚:从 doInBackground() 方法):您只需在上下文中运行 runOnUiThread() 方法。就我而言,我是从doInBackground() body 调用它。
ContactsViewerActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(ContactsViewerActivity.this);
builder.setTitle("Connection problem..")
.setMessage("Could not connect to " + url + ", " +
"try changing your host in the settings to default one :" +
getResources().getString(R.string.default_server_ip) + ":" +
getResources().getString(R.string.default_server_port))
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
【解决方案5】:
您可以直接从 doInBackground() 调用 publishProgress() 并在 onProgressUpdate() 中使用 UI 进行操作。