Android WebView BadTokenException 异常修复

titleAndroid WebView 异常修复
date2017-02-15 19:57:05
tags[Android,WebView,Summary]
categoriesAndroid

今天测试反馈了一个十分诡异的问题。先看场景。

操作步骤

1.访问淘宝首页
2.点击登录
3.免费注册
4.在免费注册界面,点击 国家/地区
–>Crash
Logcat 显示的信息如下


android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:582)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:74)
    at android.app.Dialog.show(Dialog.java:298)
    at com.android.org.chromium.content.browser.input.SelectPopupDialog.show(SelectPopupDialog.java:126)
    at com.android.org.chromium.content.browser.ContentViewCore.showSelectPopup(ContentViewCore.java:2569)
    at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
    at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:28)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5318)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:922)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:717)

看到这些错误日志,都是Framework层的代码,没有应用层的调用信息。

我们在对比下,正常情况下的响应应该是什么样子。

《Android WebView BadTokenException 异常修复》 国家/地区 正常响应

由于这个功能,在我们主模块中是OK的,但是在信息流模块中是有问题的,首先的反应就是,对比关键代码差异。

茫茫代码深似海,要找到点滴差异,谈何容易。看了各个回调,每个设置接口,都没卵用。最后直接搜索问题原因!

感谢万能的Google,StackOverflow

在 Stackoverflow 上,有个同样的问题,答复是这样的。

When you create the WebView you are currently using the context of the application. You should be using the context of the Activity. To solve the problem, replace getApplicationContext() with this when you create the WebView.

原始链接在这里

Android BadTokenException when using a WebView Container

在创建 WebView 的时候,要使用 Activity ,如果使用 ApplicationContext,创建Dialog时,获取不到Window的token。为什么Activity的Context可以获取到token,ApplicationContext无法获取,这儿要深入到源码里查看,有兴趣的自行查找。

我们项目代码中,在创建WebView时,之前为了避免WebView造成的内存泄露,使用了ApplicationContext,而主模块默认传入Activity。

问题的修复方法很简单,创建WebView 的时候,传入Activity类型参数。

    原文作者:imesong
    原文地址: https://www.jianshu.com/p/ed97fef1829f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞