android - 如何在 onReceivedError 后恢复刷新的 Web View

标签 android webview refresh

我正在开发我正在调用网页的小应用程序。

我想在同一 View 中打开网页时覆盖 WebViewClient。

我的问题是如果发生任何问题(互联网连接中断或服务器断开连接),那么我将显示自定义错误页面。

但是当 Internet 连接时,它显示相同的错误页面,而不是刷新的网页。

这是我的代码:
Web查看问题web;
字符串问题网址;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    DetectConnection detectConnection = new DetectConnection(getApplicationContext());
    ActionBar bar = getActionBar();

    // for color
    bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#5b5959")));
    questionweb = (WebView) findViewById(R.id.webView1);
    if (!DetectConnection.checkInternetConnection(this)) {
        Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
        AlertDialog alertDialog = new AlertDialog.Builder(
                MainActivity.this).create();

        // Setting Dialog Title
        alertDialog.setTitle("Internet Connection");

        // Setting Dialog Message
        alertDialog.setMessage("Please Check Internet Connection");

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to execute after dialog closed
                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                MainActivity.this.startActivity(intent);
            }
        });

        // Showing Alert Message
        alertDialog.show();

    } else {

    questionweb.getSettings().setJavaScriptEnabled(true);

    // loads the WebView completely zoomed out
    questionweb.getSettings().setLoadWithOverviewMode(true);


    questionweb.getSettings().setUseWideViewPort(true);

    // override the web client to open all links in the same webview
    questionweb.setWebViewClient(new MyWebViewClient());
    questionweb.setWebChromeClient(new MyWebChromeClient());


    questionweb.addJavascriptInterface(new JavaScriptInterface(this),
            "Android");

    // load the home page URL
    questionweb.loadUrl("http://10.2.1.119:8081/OnlineExamV2/login/loginpage");

    }
    // I am calling this to refresh the webpage
    questionweb.loadUrl("javascript:window.location.reload( true )" );  

}

private class MyWebViewClient extends WebViewClient {

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
         super.onReceivedError(view, errorCode, description, failingUrl);
         hideErrorPage(view);
    }

    private void hideErrorPage(WebView view) {

        String customErrorPageHtml = "<html><body><table width=\"100%\" height=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"
                + "<tr>"
                + "<td><div align=\"center\"><font color=\"red\" size=\"22pt\">Sorry! Something went wrong</font></div></td>"
                + "</tr>" + "</table><html><body>";
        view.loadData(customErrorPageHtml, "text/html", null);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         questionweb.loadUrl(url);
        //questionweb.loadUrl("http://10.2.1.119:8081/OnlineExamV2/login/loginpage");

        questionweb.clearHistory();
        return true;
    }



}

private class MyWebChromeClient extends WebChromeClient {

    // display alert message in Web View
    @Override
    public boolean onJsAlert(WebView view, String url, String message,
            JsResult result) {
        Log.d("Web", message);
        new AlertDialog.Builder(view.getContext()).setMessage(message)
                .setCancelable(true).show();
        result.confirm();
        return true;
    }



}

如何在互联网恢复时刷新网页。

最佳答案

也许您可以试一试自己的 BroadcastReceiver 类。

像这样尝试(完全未经测试):

1.) GlobalState 类:

public GlobalState {

    public static boolean isOnline = true;
    public static String lastUrl = ""; 
}

2.) 在 onReceivedError 中保存上一个 url 和连接状态:
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

     super.onReceivedError(view, errorCode, description, failingUrl);
     GlobalState.isOnline = false;
     GlobalState.lastUrl = failingUrl;

     hideErrorPage(view);
}

3.)在你的 Activity 类中实现一个回调(我不知道名字,所以我称之为 MainActivity.java):
public class MainActivity extends Activity implements IConnectionCallback {

    private ConnectionBroadReceiver cbr = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //some code...
        cbr = new ConnectionBroadReceiver (this);
        registerReceiver(cbr, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 
       //some more code...        
    }

    //this method will be triggered by ConnectionBroadCastReceiver
    @Override
    public void reload() {

        //now reload your webview:
        questionweb.loadUrl(GlobalState.lastUrl);
    }
}

4.) 定义你的接口(interface)回调:
public interface IConnectionCallback {

    public void reload();
}

5.) 最后但并非最不重要的 ConnectionBroadReceiver 类:
public class ConnectionBroadReceiver extends BroadcastReceiver {

    private IConnectionCallback callback = null;

    public ConnectionBroadReceiver (IConnectionCallback callback) {

        this.callback = callback;

    }

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager cm = (ConnectivityManager)    
        context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        // lets check the connection
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {

            //when last state was the offline state (GlobalState.isOnline== false), 
            //lets trigger the callback 
            if (GlobalState.isOnline == false) {

                callback.reload();
            }
            GlobalState.isOnline = true;
         } else {

            GlobalState.isOnline = false;
     }

}

关于android - 如何在 onReceivedError 后恢复刷新的 Web View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24955139/

相关文章:

java - 如何使用变量来启动新的 Intent

javascript - 有没有办法动态编辑WebView中显示的内容?

android - WebView 无限扩展 - 如何防止这种情况发生?

ajax - Bootstrap Select 'refresh"继续添加新选项而不是删除旧选项

javascript - 选取框文本在刷新时发生变化

android - 可绘制位图不适用于 Android < 5

android - Firebase UI gradle 无法解析 'com.firebaseui.firebase-ui:0.2.0'

android - 通过淡入和放大动画 View 可见性

cocoa - Mac OS X 上带有 Cocoa WebView 的综合 Web 服务器

ajax - Jquery mobile - 用于通过 ajax 创建的动态 html 内容的单选按钮小部件