优化点1( 显示时机问题)
要求进入界面就在某个空间上显示一张用来引导用户的图片,项目中这里出现了两个问题
1.因为巧合,进入界面做了很多初始化动作之后再show,碰巧没有遇到这个问题
Caused by: android.view.WindowManager$BadTokenException: Unable to add window – token null is not valid; is your activity running?
2.进入界面初始化时间不定,比较长(因为有调用接口的缘故),导致用户时候时候总是可以看到popupwindow由无到有的过程
以上两个问题都是因为显示的时机不对造成的,解决方案如下:
//给控件添加布局监听,等待全部布局初始化完毕后再显示,并且记得反注册
imgReboot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//这里做展示的一些操作,为了防止popwindow重复创建多个重叠,在这里判断对象是否为null
imgReboot.getViewTreeObserver().removeOnGlobalLayoutListener(this);//因为onGlobalLayout会进入多次,展示完毕将这个观察者回调反注册,提交代码效率,否则多次进入没有意义
}
});
优化点2(window leaded)
在popupwindow没有关闭的情况下,关闭宿主,导致window leaked
窗体泄露日志如下
android.view.WindowLeaked: Activity com.spd.ehr.activity.main.MainActivity has leaked window android.widget.PopupWindow$PopupViewContainer{422e2bd8 V.E..... ......I. 0,0-216,162} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:368)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:252)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.widget.PopupWindow.invokePopup(PopupWindow.java:1019)
at android.widget.PopupWindow.showAtLocation(PopupWindow.java:850)
at android.widget.PopupWindow.showAtLocation(PopupWindow.java:814)
at com.spd.ehr.activity.main.MainActivity.showGuidePopup(MainActivity.java:193)
at com.spd.ehr.activity.main.MainActivity.access$000(MainActivity.java:51)
at com.spd.ehr.activity.main.MainActivity$1.onGlobalLayout(MainActivity.java:156)
at android.view.ViewTreeObserver.dispatchOnGlobalLayout(ViewTreeObserver.java:815)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1828)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1046)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5663)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5052)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)
解决方案:如果窗口(popupwindow或者dialog)没有dismiss,在ondestory中先做dismiss
版权声明:本文为nongminkouhao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。