Android Bug记录–WebView UserAgent

  • 4,197 views
  • 阅读模式

错误日志:

java.lang.IllegalStateException: Calling View methods on another thread than the UI thread.
    at com.android.webview.chromium.WebViewChromium.createThreadException(WebViewChromium.java:67)
    at com.android.webview.chromium.WebViewChromium.checkThread(WebViewChromium.java:75)
    at com.android.webview.chromium.WebViewChromium.init(WebViewChromium.java:30)
    at android.webkit.WebView.<init>(WebView.java:636)
    at android.webkit.WebView.<init>(WebView.java:572)
    at android.webkit.WebView.<init>(WebView.java:555)
    at android.webkit.WebView.<init>(WebView.java:542)
    at android.webkit.WebView.<init>(WebView.java:532)
    at com.itlao5.app.getUser_agent(Utils.java:123)
    at com.itlao5.app.NetsUtils$1.doInBackground(NetsUtils.java:54)
    at com.itlao5.app.net.NetsAsyncTask$2.run(NetsAsyncTask.java:27)

同一段代码在原本的demo中使用没有问题,但是移植到项目中就报上述错误,即使加上了try~catch(Exception)也不能起作用。

查阅文档:http://developer.android.com/intl/zh-cn/guide/webapps/migrating.html
原来,在4.4之后就不能在主线程new Webview(ctx)了,不过文档中提供的方法:

If you need to retrieve the user agent but don't need to store it for your app or do not want to instantiate WebView, you should use the static method, getDefaultUserAgent(). However, if you intend to override the user agent string in your WebView, you may instead want to use getUserAgentString().

于是,原本的代码new WebView(context).getSettings().getUserAgentString()修改为:

public static String getUserAgent(Context ctx) {
        //api 19 之前
        if(Build.VERSION.SDK_INT < 19){
            return  new WebView(ctx).getSettings().getUserAgentString();
        }
        //api >=19
        return WebSettings.getDefaultUserAgent(ctx);
    }

weinxin
扫码关注微信公众号--IT老五
微信扫一扫关注公众号,获取更多实用app,订阅地址不定时更新
Liu, Thinkin
  • 本文由 发表于 2018-06-05 15:20:08
  • 转载请务必保留本文链接:https://itlao5.com/422.html
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定