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

原文:简书ThinkinLiu 博客: IT老五

于是,原本的代码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);
    }

猜你喜欢

转载自blog.csdn.net/andy_5826_liu/article/details/84097359