我尝试使用 WebView 加载 URL,但 Web 视图似乎不稳定 - 有时页面加载 100%,有时它停止加载 30%/50%/75%(随机)。我在 Android Bolts 任务中创建了 WebView,并且没有向用户显示 WebView,它只为将来的请求加载一些 javascript。
代码:
private Task<Boolean> task_SetupJavascript(){
final Task<Boolean>.TaskCompletionSource myTask = Task.create();
WebView webview = new WebView(getActivity());
final WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript: LocalStorage.set('valueA', 'valueB', 'valueC');");
myTask.setResult(Boolean.TRUE);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
// never fired during tests
Log.e(TAG,"onReceivedError ---> Something went wrong... ");
myTask.setCancelled();
}
});
webview.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
Log.e(TAG, ""+newProgress);
}
});
webview.loadUrl(URL);
webview.onResume();
return myTask.getTask();
}
我无法弄清楚是什么导致 WebView 在进度中间随机停止加载。有时它在第一次运行此任务时失败,有时在 3/4/5 次后失败。