开发者

Webview check for connectivity through out session

开发者 https://www.devze.com 2023-02-04 02:59 出处:网络
I have a WebView app, and need to check for an Internet connection with every action \"click\" inside the app.I got the following code working to check the internet on start up of the app.But I need t

I have a WebView app, and need to check for an Internet connection with every action "click" inside the app. I got the following code working to check the internet on start up of the app. But I need to figure out how to have this check every time the user changes pages with in the webview.

My code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if(!isNetworkConnectionAvailable()){
        Context context = getApplicationContext();
        CharSequence text = "Sorry you need an Internet connection!  Please try again when th开发者_如何学JAVAe network" +
                " is available.";
        int duration = Toast.LENGTH_LONG;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();

        finish();
    }

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl("http://example.com/");

    mWebView.setWebViewClient(new MyAppViewClient());
}

And this is my connection checking code:

    public boolean isNetworkConnectionAvailable() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 

    if (netInfo != null && netInfo.isConnectedOrConnecting()){ 
        return true;
    }
    else{
        return false;
    } 

}

Is this possible?


I think you can detect a new URL loaded request this way:

private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

I learned to override that function so that clicking on a link in a webview does not open a new activity. That function is called each time a user clicks on a URL. I think you may be able to hook your connection check logic there.

I am curious though as to why you need to check this. The webview control will show an error if there is no connection. Are you just trying to short-circuit that error message? There could be a very small timing window where your check succeeds, but then the website becomes unavailable when the click is processed.

Hope this helps, Kevin

0

精彩评论

暂无评论...
验证码 换一张
取 消