天天看點

簡書 android bug記錄,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.(WebView.java:636)

at android.webkit.WebView.(WebView.java:572)

at android.webkit.WebView.(WebView.java:555)

at android.webkit.WebView.(WebView.java:542)

at android.webkit.WebView.(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)也不能起作用。

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

}