1. 程式人生 > >Android Bug記錄--WebView UserAgent

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);
    }