WebView在加载页面时需要很长时间才能关闭互联网连接
问题描述:
我在android应用程序上工作,并且我有一个webview显示用户的一些web内容。WebView在加载页面时需要很长时间才能关闭互联网连接
现在我尝试做一些集成测试用例,以确保所有的东西都是正确的。
其中一个测试用例是在加载页面期间关闭互联网连接并检查行为。
这是我的代码:
@Override
public void initializeWebViewCallbacks() {
if(!InternetHelper.isThereInternetConnection(AuthFragment.this.context()))
{
AuthFragment.this.showRetry();
}
else{
wv_auth.setWebViewClient(new WebViewClient());
wv_auth.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv_auth.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
if (Build.VERSION.SDK_INT >= 19) {
wv_auth.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else {
wv_auth.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
wv_auth.loadUrl("http://myurl");
wv_auth.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
wv_auth.setVisibility(View.GONE);
AuthFragment.this.hideLoading();
AuthFragment.this.showRetry();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
AuthFragment.this.showLoading();
}
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@TargetApi(android.os.Build.VERSION_CODES.M)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return shouldOverrideUrlLoading(view, request.toString());
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
AuthFragment.this.hideLoading();
// some code
new Handler().postDelayed(new Runnable() {
public void run() {
((BaseActivity)getActivity()).navigator.navigateToMainActivity(AuthFragment.this.getActivity(),false);
}
}, 200);
}
}
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view,errorCode,description,failingUrl);
// Handle the error
wv_auth.setVisibility(View.GONE);
AuthFragment.this.hideLoading();
AuthFragment.this.showRetry();
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
}
}
当我关掉装载仪在互联网连接的页面,进度圈约30分钟仍在运行和突破点,通过onReceivedError没去(... )所以我不能处理这种情况下,有什么建议?
答
我认为这是loadUrl(..)方法的问题。
我尝试了所有可能的解决方案,并在此处遵循所有解决方案:SO question但没有机会。
我注意到,当您创建承载webview的活动或片段时,每件事情都可以正常工作,因此我通过导航到另一个中间空白活动达到了1秒,然后返回到此活动并通过此解决了问题。
请参阅“loaderTask”:: http://stackoverflow.com/questions/22759978/android-timeout-webview-if-it-takes-longer-than-a-certain-time-to-load –