问题
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.
mWebView.setVisibility(View.VISIBLE);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setMinimumFontSize(14);
String htmlContent = "<?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(htmlContent, "text/html; charset=utf-8", "UTF-8");
As a result, how can I solve this problem?
回答1:
I solved my problem, the problem occurs in Smartphones that has latest Chrome.
SOLUTION:
Do not use
mWebview.loadData
method, instead use
mWebview.loadDataWithBaseURL
As a result my solution is:
mWebview.loadDataWithBaseURL(null,htmlContent,"text/html", "utf-8", null);
回答2:
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.
回答3:
I too had the same problem with Android Version 9.0
The documents at this page (https://developer.android.com/about/versions/pie/android-9.0-migration) 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()
try {
String base64 = null;
base64 = android.util.Base64.encodeToString(lecureHtmlData.getBytes("UTF-8"),
android.util.Base64.DEFAULT);
wvLecture.loadData(base64, "text/html; charset=utf-8", "base64");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Now it is working as usual.
Hope it helps
来源:https://stackoverflow.com/questions/54516798/webview-loaddata-not-working-on-8-1-and-9-0