我有一个启动 AsyncTask 并在操作期间显示进度对话框的 Activity 。声明该 Activity 不会通过旋转或键盘滑动重新创建。
<activity android:name=".MyActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation"
>
<intent-filter>
</intent-filter>
</activity>
任务完成后,我会关闭对话框,但在某些手机(框架:1.5、1.6)上会抛出此类错误:
java.lang.IllegalArgumentException: View not attached to window manager
at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:356)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:201)
at android.view.Window$LocalWindowManager.removeView(Window.java:400)
at android.app.Dialog.dismissDialog(Dialog.java:268)
at android.app.Dialog.access$000(Dialog.java:69)
at android.app.Dialog$1.run(Dialog.java:103)
at android.app.Dialog.dismiss(Dialog.java:252)
at xxx.onPostExecute(xxx$1.java:xxx)
我的代码是:
final Dialog dialog = new AlertDialog.Builder(context)
.setTitle("Processing...")
.setCancelable(true)
.create();
final AsyncTask<MyParams, Object, MyResult> task = new AsyncTask<MyParams, Object, MyResult>() {
@Override
protected MyResult doInBackground(MyParams... params) {
// Long operation goes here
}
@Override
protected void onPostExecute(MyResult result) {
dialog.dismiss();
onCompletion(result);
}
};
task.execute(...);
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
task.cancel(false);
}
});
dialog.show();
根据我阅读的内容 (http://bend-ing.blogspot.com/2008/11/properly-handle-progress-dialog-in.html) 并在 Android 源代码中看到,似乎唯一可能出现该异常的情况是 Activity 被破坏时。但正如我所提到的,我禁止为基本事件进行 Activity 娱乐。
所以任何建议都非常感谢。
最佳答案
当我从 onPostExecute 方法关闭对话框并完成 Activity 时,有时也会收到此错误。我想有时 Activity 会在对话框成功关闭之前完成。
适合我的简单而有效的解决方案
@Override
protected void onPostExecute(MyResult result) {
try {
if ((this.mDialog != null) && this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.mDialog = null;
}
}
关于android - java.lang.IllegalArgumentException : View not attached to window manager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2745061/