我试图将Andersen的文章“丑小鸭”(HTML)加载到Android上的WebClient中,这是我的代码。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupWebClient();
}
private void setupWebClient() {
WebView webView = findViewById(R.id.webView);
String html = readTestHtml();
Long start = System.currentTimeMillis();
webView.loadData(html, "text/html", "UTF-8");
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
Long end = System.currentTimeMillis();
Log.i("test", String.format("Cost %dms", end - start));
}
});
}
/**
* Read HTML from "/sdcard/Download/test.html", which is "The ugly duckling" in Chinese.
*/
private String readTestHtml() {
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(downloads,"test.html");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
return text.toString();
}
}
已加载的文章用中文撰写。完成加载花费了7654毫秒。但是,当我将文章替换为英文版本时,它的速度要快得多,只需375毫秒即可完成。 WebClient似乎在解析汉字时遇到一些麻烦。我可以做些什么使它更快地解析汉字吗?
测试材料和装置:请注意,基于x86的仿真器没有此问题。我只能在真实手机上重现此问题。