11package com .hjq .toast ;
22
3+ import android .app .Activity ;
34import android .app .Application ;
5+ import android .content .Context ;
46import android .graphics .PixelFormat ;
57import android .os .Handler ;
68import android .os .Looper ;
@@ -95,16 +97,24 @@ void show() {
9597 params .y = mToast .getYOffset ();
9698
9799 try {
98- // 如果这个 View 对象被重复添加到 WindowManager 则会抛出异常
99- // java.lang.IllegalStateException:
100- // View android.widget.TextView has already been added to the window manager.
101- mWindowHelper .getWindowManager ().addView (mToast .getView (), params );
100+ Activity topActivity = mWindowHelper .getTopActivity ();
101+ if (topActivity != null && !topActivity .isFinishing ()) {
102+ WindowManager windowManager = (WindowManager ) topActivity .getSystemService (Context .WINDOW_SERVICE );
103+ if (windowManager != null ) {
104+ windowManager .addView (mToast .getView (), params );
105+ }
106+ }
102107 // 添加一个移除吐司的任务
103108 sendEmptyMessageDelayed (hashCode (), mToast .getDuration () == Toast .LENGTH_LONG ?
104109 IToastStrategy .LONG_DURATION_TIMEOUT : IToastStrategy .SHORT_DURATION_TIMEOUT );
105110 // 当前已经显示
106111 setShow (true );
107- } catch (NullPointerException | IllegalStateException | WindowManager .BadTokenException ignored ) {}
112+ } catch (IllegalStateException | WindowManager .BadTokenException ignored ) {
113+ // 如果这个 View 对象被重复添加到 WindowManager 则会抛出异常
114+ // java.lang.IllegalStateException: View android.widget.TextView has already been added to the window manager.
115+ // 如果 WindowManager 绑定的 Activity 已经销毁,则会抛出异常
116+ // android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@ef1ccb6 is not valid; is your activity running?
117+ }
108118 }
109119 }
110120
@@ -116,11 +126,17 @@ void cancel() {
116126 removeMessages (hashCode ());
117127 if (isShow ()) {
118128 try {
129+ Activity topActivity = mWindowHelper .getTopActivity ();
130+ if (topActivity != null ) {
131+ WindowManager windowManager = (WindowManager ) topActivity .getSystemService (Context .WINDOW_SERVICE );
132+ if (windowManager != null ) {
133+ windowManager .removeViewImmediate (mToast .getView ());
134+ }
135+ }
136+ } catch (IllegalArgumentException ignored ) {
119137 // 如果当前 WindowManager 没有附加这个 View 则会抛出异常
120- // java.lang.IllegalArgumentException:
121- // View=android.widget.TextView not attached to window manager
122- mWindowHelper .getWindowManager ().removeViewImmediate (mToast .getView ());
123- } catch (NullPointerException | IllegalArgumentException ignored ) {}
138+ // java.lang.IllegalArgumentException: View=android.widget.TextView not attached to window manager
139+ }
124140 // 当前没有显示
125141 setShow (false );
126142 }
0 commit comments