How to get back refreshed web view after onReceivedError

佐手、 提交于 2019-12-21 06:00:07

问题


I am developing small app where I am calling webpage.

I override WebViewClient as I wants to open webpage in same view.

My problem is if there is any problem occur(Internet connection breaks or server is disconnected) then I am showing custom error page.

But when Internet is connected it shows same error page, not refreshed web page.

Here is my code: WebView questionweb; String questionurl;

@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;
    }



}

How to get refreshed web page When internet is back.


回答1:


Maybe you can give your own BroadcastReceiver class a shot.

Try it like this (totally untested):

1.) GlobalState class:

public GlobalState {

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

2.) Save your last url and connection-state in onReceivedError:

@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.) Implement a callback in your activity class (i do not know the name, so i called it 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.) Define your Interface callback:

public interface IConnectionCallback {

    public void reload();
}

5.) Last but not least the ConnectionBroadReceiver class:

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;
     }

}


来源:https://stackoverflow.com/questions/24955139/how-to-get-back-refreshed-web-view-after-onreceivederror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!