Android Bug记录–WebView UserAgent

itlao6 原创 开发&源码 Android评论1,063字数 1449阅读4分49秒阅读模式

错误日志:

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)也不能起作用。文章源自IT老刘-https://itlao6.com/422.html

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

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().文章源自IT老刘-https://itlao6.com/422.html

于是,原本的代码new WebView(context).getSettings().getUserAgentString()修改为:文章源自IT老刘-https://itlao6.com/422.html

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);
    }
文章源自IT老刘-https://itlao6.com/422.html文章源自IT老刘-https://itlao6.com/422.html
继续阅读
weinxin
我的微信公众号
微信扫一扫关注公众号,不定时更新
itlao6
  • 本文由 发表于 2018年 6月 5日 15:20:08
  • 转载请务必保留本文链接:https://itlao6.com/422.html
评论  0  访客  0
匿名

发表评论

匿名网友

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

确定