我有一个Android Webview代码,该代码无法检测到小于21的API的HTTP错误。
我尝试过的事情:
已经进行了多次尝试和错误
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent);
Toast.makeText(getApplicationContext(), "Error occured, please check Network Connectivity", Toast.LENGTH_SHORT).show();
super.onReceivedError(view, errorCode, description, failingUrl);
}
另一种方法:
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if(error.getErrorCode() == -8 || error.getErrorCode() == -14 || error.getErrorCode() == -6){
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent);
mWebview.clearCache(true);
Toast.makeText(getApplicationContext(), "Error occured, please check Network Connectivity", Toast.LENGTH_SHORT).show();
}
super.onReceivedError(view, request, error);
}
它们都不起作用。 onReceivedHttpError 正常运行,但仅适用于21以上的API。
在堆栈上引用了各种帖子,但结果始终相同。
如果有人可以指出潜在问题,这将非常有帮助。
代码:
package com.test.example;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import static android.content.ContentValues.TAG;
public class MainActivity extends Activity {
public static WebView mWebview;
private android.content.Context Context;
private static String getIntentValue = null;
public static SharedPreferences sharedPreferences;
private ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context = this;
getIntentValue = getIntent().getStringExtra("value");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String token1 = sharedPreferences.getString("regtoken", null);
Log.d(TAG, "TOKEN===>" + token1);
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet Connection!", Toast.LENGTH_LONG).show();
finish(); //Calling this method to close this activity when internet is not available.
} else {
mWebview = (WebView) findViewById(R.id.webview1);
WebSettings webSettings = mWebview.getSettings();
mWebview.getSettings().setJavaScriptEnabled(true);
CookieManager.getInstance().setAcceptCookie(true);
mWebview.setWebChromeClient(new WebChromeClient());
mWebview.setWebChromeClient(new JsPopupWebViewChrome());
mWebview.setWebViewClient(new CustomWebViewClient());
//improve WebView Performance
mWebview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebview.getSettings().setAppCacheEnabled(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
// progress dialog
mProgressDialog = new ProgressDialog(Context);
if (sharedPreferences.getBoolean("isKeyGenerated", true)) {
if (getIntentValue != null) {
mWebview.loadUrl("http://www.example.com");
getIntentValue = null;
} else {
mWebview.loadUrl("http://www.example.com");
}
}
}
}
private class JsPopupWebViewChrome extends WebChromeClient {
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder b = new AlertDialog.Builder(view.getContext())
.setTitle("ALERT!")
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
b.show();
// Indicate that we're handling this manually
return true;
}
}
// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(Context)) {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
} else if (url.startsWith("http://www.example.com")) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Say Bye Bye to Hospital Waiting!!!.\n\n\nDownload This App to BOOK & Keep Track of your Number in Hospital.\n\nhttp://www.example.com";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "test");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
} else if (url.contains("youtube")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
//on page started, show loading page
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
@Override
public void onPageFinished(WebView view, String url)
{
String currentPage= mWebview.getUrl();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("currentpage",currentPage);
editor.commit();
//after loading page, remove loading page
// TODO Auto-generated method stub
super.onPageFinished(view, url);
mProgressDialog.dismiss();
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent);
Toast.makeText(getApplicationContext(), "Error occured, please check Network Connectivity", Toast.LENGTH_SHORT).show();
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if(errorResponse.getStatusCode() == 408 || errorResponse.getStatusCode() == 404){
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent);
mWebview.clearCache(true);
Toast.makeText(getApplicationContext(), "Error occured, please check Network Connectivity", Toast.LENGTH_SHORT).show();
}
}
super.onReceivedHttpError(view, request, errorResponse);
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if(error.getErrorCode() == -8 || error.getErrorCode() == -14 || error.getErrorCode() == -6){
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent);
mWebview.clearCache(true);
Toast.makeText(getApplicationContext(), "Error occured, please check Network Connectivity", Toast.LENGTH_SHORT).show();
}
super.onReceivedError(view, request, error);
}
}
//-------------
@Override
public void onBackPressed() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String currenturl = sharedPreferences.getString("currentpage", null);
mWebview.requestFocus();
if (currenturl.contains("http://www.example.com")){
moveTaskToBack(true);
}else{
mWebview.goBack();
}
}
public static void loadUrl(String key) {
if (getIntentValue != null) {
mWebview.loadUrl("http://www.example.com");
getIntentValue = null;
} else {
mWebview.loadUrl("http://www.example.com");
}
}
public static void reLoad() {
mWebview.reload();
}
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}