Android Bug记录--WebView UserAgent

错误日志:

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().

个人博客: IT老五
微信公众号:【IT老五(it-lao5)】,一起源创,一起学习!

于是,原本的代码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);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • By clicking to agree to this Schedule 2, which is hereby ...
    qaz0622阅读 5,389评论 0 2
  • by Lene Nielsen The persona method has developed from bei...
    鲜核桃阅读 4,935评论 0 0
  • 疏明酣欢弄闲窗,添衣温酒愈薄凉。 知我山秋魂野客,长安不见影寒惶。
    存_962b阅读 1,729评论 0 1
  • 2017年9月18 建群初心 无意间搜索到本元自我教练公纵号,看到自我教练认证课连载,第一课就是人和动物、机...
    lily北妈阅读 825评论 0 0