最近公司项目上线之前用Monkey测试,一直出这个错误:Exception: View not attached to window manager。特别纠结,后来总结了下,就是在Activity消失的情况下,还调用dialog的dismiss方法就出这个错误了。我的解决办法是:
判断当前的activity.isFinishing() + !=null + isShowing(),这三种方式去防止发生这个问题。
Exception: View not attached to window manager/ProcessDialog调用是屏幕旋转抛出异常01-28 14:09:07.889: ERROR/AndroidRuntime(5084): java.lang.IllegalArgumentException: View not attached to window manager
01-28 14:09:07.889: ERROR/AndroidRuntime(5084): at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:355)
01-28 14:09:07.889: ERROR/AndroidRuntime(5084): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:200)
01-28 14:09:07.889: ERROR/AndroidRuntime(5084): at android.view.Window$LocalWindowManager.removeView(Window.java:432)
01-28 14:09:07.889: ERROR/AndroidRuntime(5084): at android.app.Dialog.dismissDialog(Dialog.java:278)
在Dialog转圈圈的过程中,如果手机屏幕方向改变,那么可能会抛出这个异常,原因就是屏幕翻转后那些view重新画出来,dialog在执行dismiss()的时候,
找不到原来的位置了。那么要处理这个问题,最简单的几种方法是:
1. 限制屏幕翻转
可在AndroidManifest.xml中设定android:screenOrientation=”portrait”
2. 如果是需要翻转的,那么限制那些view做重画动作。
可在AndroidManifest.xml中设定android:configChanges=”orientation|keyboardHidden|navigation”
3. 如果你又要翻转,又要重画view,那你就用代码去控制
private void lockScreen(){
Configuration newConfig = getResources().getConfiguration();
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){ //横屏
U.dout("ORIENTATION_LANDSCAPE lock it!");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ //竖屏
U.dout("SCREEN_ORIENTATION_PORTRAIT lock it!");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if(newConfig.hardKeyboardHidden == Configuration.KEYBOARDHIDDEN_NO){ //键盘没关闭。屏幕方向为横屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else if(newConfig.hardKeyboardHidden == Configuration.KEYBOARDHIDDEN_YES){ //键盘关闭。屏幕方向为竖屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
private void unlockScreen(){
U.dout("unlock!");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
参考:
http://www.2cto.com/kf/201202/119310.html