您的位置:首页 > 编程语言 > Java开发

使用Activity.isfinishing()解决java.lang.IllegalArgumentException: View not attached to window manager

2016-07-23 09:47 686 查看
在页面中使用了dialog、popwindow等弹框控件的时候,有时候会报java.lang.IllegalArgumentException: View not attached to window manager异常,怎么来的呢

看日志信息:

java.lang.IllegalArgumentException: View not attached to window manager

at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:588)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:325)
at android.view.WindowManagerImpl$CompatModeWrapper.removeView(WindowManagerImpl.java:152)
at android.app.Dialog.dismissDialog(Dialog.java:341)
at android.app.Dialog$1.run(Dialog.java:123)
at android.app.Dialog.dismiss(Dialog.java:326)
at com.********.ShakeActivity1$2.processData(ShakeActivity1.java:197)
at com*********.ShakeActivity1$2.processData(ShakeActivity1.java:1)
at com.********.BaseActivity$BaseHandler.handleMessage(BaseActivity.java:201)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4624)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:965)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:732)
at dalvik.system.NativeStart.main(Native Method)


从上面的日志信息可以看出,报错的地方是dialog调用dismiss方法的时候。

java代码如下:

if (dialog != null) {
dialog.dismiss();
}

可以看到,dialog不为空,那么是怎么报的异常呢?随后我查阅了网上大多数的解决方法,总结了报错原因。这是由于因意外情况导致activity比dialog销毁的早,然后调用到dialog的方法时会发现没有activity依附,这一点从日志中就可以看出。

解决方法:

1、在页面的destory方法中,判断dialog是否存在,若存在,dismiss就销毁,使dialog的生命周期与activity同步;

2、在一些由于耗时操作或其他操作导致容易出现activity被销毁而dialog未销毁的地方,使用activity.isfinidhing方法判断activity是否被销毁,销毁,则终止代码;

PS:activity.isfinishing的官方API:

Check to see whether this activity is in the process of finishing, either because you called
finish()
on it or someone else
has requested that it finished. This is often used in
onPause()
to determine whether the activity is simply pausing or completely
finishing.

Returns
If the activity is finishing, returns true; else returns false.

翻译过来就是,isfinishing方法为true,当前页面销毁,反之亦然。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: