美文网首页
Android 9.0 适配:WebView.loadData(

Android 9.0 适配:WebView.loadData(

作者: 好学人 | 来源:发表于2019-07-27 21:14 被阅读0次

参考资料:https://stackoverflow.com/questions/54516798

WebView.loadData not working on Android 8.1 and 9.0

I have an article app, I am showing articles in webview. In android version 8.1 and 9.0 This webview is not working. The app shows NOTHING in article activity.

String html = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
              + "<head>"
              + "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
              + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>"
              + "<style type=\"text/css\">body{color: #525252;} img {max-width: 100%; height: auto}</style>"
              + "</head>"
              + item.getContent() //content of item";

mWebView.loadData(html, "text/html; charset=utf-8", "UTF-8");

As a result, how can I solve this problem ?

Answer from dna

I too had the same problem with Android Version 9.0

The documents at this page mention that:

In Android 9, the UTF-8 decoder for Java language is stricter and follows the Unicode standard.

So I tried converting the UTF-8 into Base64 and use loadData()

String base64Html = Base64.encodeToString(htmlData.getBytes("UTF-8"), Base64.DEFAULT);
webView.loadData(base64Html , "text/html; charset=utf-8", "base64");

Now it is working as usual.

Hope it helps

Answer from gurkan stack

I solved my problem, the problem occurs in Smartphones that has latest Chrome.

SOLUTION:

Do not usemWebview.loadData(), method, instead usemWebview.loadDataWithBaseURL().

As a result my solution is:

mWebview.loadDataWithBaseURL(null,htmlContent,"text/html", "utf-8", null);

Answer from Yuichi Araki

Your HTML content should be either Base64 or URL encoded. Your HTML example has a # in it, and it causes the problem on some WebView versions.

Here's an example with Base64 encoding.

String htmlContent = "...";
String encodedHtml = Base64.encodeToString(htmlContent.getBytes(), Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");

Here's javadoc for detail.

相关文章

网友评论

      本文标题:Android 9.0 适配:WebView.loadData(

      本文链接:https://www.haomeiwen.com/subject/qyqyrctx.html