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

本文深入探讨了在Android应用中使用对话框(dialog)时遇到的View not attached to window manager异常,分析了异常产生的原因,并提供了两种有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在页面中使用了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 calledfinish() on it or someone else has requested that it finished. This is often used inonPause() to determine whether the activity is simply pausing or completely finishing.

Returns
  • If the activity is finishing, returns true; else returns false.
翻译过来就是,isfinishing方法为true,当前页面销毁,反之亦然。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值