28

我有一个带有 webview 的 Android 应用程序。当没有互联网连接时,webview 将显示页面不可用。我想让这个看起来尽可能像一个应用程序,所以我不想显示这个页面。我在网上找到了一些有用的信息,教你如何隐藏或加载其他内容来覆盖它,但我真正想要的是留在当前页面,然后弹出一个小对话框说没有连接。基本上,当用户单击 webview 内的任何内容时,首先检查连接。如果没有连接,则留在原来的位置并弹出一个对话框。

谢谢您的帮助!!

编辑:

就像我说的,我已经知道如何从在线样本中检查互联网连接。我的问题是我不知道如何停止加载下一页。需要明确的是,当用户尝试转到下一页时,请检查互联网连接。如果没有连接,页面将停留在原来的位置,不会转到下一页。我希望用户能够看到他们最后加载的页面并在网页内容仍然存在时得到通知。谢谢!

4

5 回答 5

48

我在我的项目中使用了以下内容:

DetectConnection.Java

import android.content.Context;
import android.net.ConnectivityManager;


public class DetectConnection {             
  public static boolean checkInternetConnection(Context context) {   

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

    return (con_manager.getActiveNetworkInfo() != null
        && con_manager.getActiveNetworkInfo().isAvailable()
        && con_manager.getActiveNetworkInfo().isConnected());
  }
}

主要代码:

if (!DetectConnection.checkInternetConnection(this)) {
  Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {      
  wv = (WebView) findViewById(R.id.donate_webView1);
  c = new CustomWebViewClient();
  wv.setWebViewClient(c);
  wv.clearCache(true);
  wv.clearHistory();
  wv.getSettings().setJavaScriptEnabled(true);
  wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
  wv.getSettings().setBuiltInZoomControls(true);
  wv.loadUrl("http://www.google.com");
}


// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (!DetectConnection.checkInternetConnection(this)) {
      Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
    } else {
      view.loadUrl(url);
    }     
    return true;
  }
}

更新清单:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2013-07-31T04:21:18.437 回答
7

你可以用我的CustomWebViewClient-

  • 在网页加载时显示加载对话框
  • 在页面加载失败时显示错误消息
  • 在没有互联网的情况下,它为用户提供了一个选项来设置和启用移动数据。
  • 如果出现其他类型的错误,它允许用户重新加载网页。

您需要做的就是将它附加到您的 webView

webView.setWebViewClient(new CustomWebViewClient ());

CustomWebViewClient 类

    /**
     * WebViewClient subclass loads all hyperlinks in the existing WebView
     */
    public class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // When user clicks a hyperlink, load in the existing WebView
            view.loadUrl(url);
            return true;
        }

        Dialog loadingDialog = new Dialog(WebViewActivity.this);

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webViewPreviousState = PAGE_STARTED;

            if (loadingDialog == null || !loadingDialog.isShowing())
                loadingDialog = ProgressDialog.show(WebViewActivity.this, "",
                        "Loading Please Wait", true, true,
                        new DialogInterface.OnCancelListener() {

                            @Override
                            public void onCancel(DialogInterface dialog) {
                                // do something
                            }
                        });

            loadingDialog.setCancelable(false);
        }


        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request,
                                    WebResourceError error) {


            if (isConnected()) {
                final Snackbar snackBar = Snackbar.make(rootView, "onReceivedError : " + error.getDescription(), Snackbar.LENGTH_INDEFINITE);
                snackBar.setAction("Reload", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        webView.loadUrl("javascript:window.location.reload( true )");
                    }
                });
                snackBar.show();
            } else {
                final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
                snackBar.setAction("Enable Data", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
                        webView.loadUrl("javascript:window.location.reload( true )");
                        snackBar.dismiss();
                    }
                });
                snackBar.show();
            }

            super.onReceivedError(view, request, error);

        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view,
                                        WebResourceRequest request, WebResourceResponse errorResponse) {

            if (isConnected()) {
                final Snackbar snackBar = Snackbar.make(rootView, "HttpError : " + errorResponse.getReasonPhrase(), Snackbar.LENGTH_INDEFINITE);

                snackBar.setAction("Reload", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        webView.loadUrl("javascript:window.location.reload( true )");
                    }
                });
                snackBar.show();
            } else {
                final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
                snackBar.setAction("Enable Data", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
                        webView.loadUrl("javascript:window.location.reload( true )");
                        snackBar.dismiss();
                    }
                });
                snackBar.show();
            }
            super.onReceivedHttpError(view, request, errorResponse);
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            if (webViewPreviousState == PAGE_STARTED) {

                if (null != loadingDialog) {
                    loadingDialog.dismiss();
                    loadingDialog = null;
                }
            }
        }
    }

检查连接方法

    /**
     * Check if there is any connectivity
     *
     * @return is Device Connected
     */
    public boolean isConnected() {

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

        if (null != cm) {
            NetworkInfo info = cm.getActiveNetworkInfo();
            return (info != null && info.isConnected());
        }

        return false;

    }
于 2017-04-13T05:57:07.653 回答
2
        webView.setWebViewClient(new WebViewClient() {
        int errorCode = 0;
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return handleUri(view, url);
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return handleUri(view, request.getUrl().toString());
        }

        private boolean handleUri(WebView view, final String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if(errorCode == 0) {
               //CHECK IS PAGE I NEED AND DO STUFF
            } else {
               errorCode = 0;
               //delay and try again
            }
        }

        @SuppressWarnings("deprecation")
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            handleError(errorCode);
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            handleError(error.getErrorCode());
        }

        private void handleError(int errorCode) {
            this.errorCode = errorCode;
        }
    });
于 2016-10-05T20:39:04.653 回答
1

您可以通过以下代码检查设备是否通过数据或 wifi 连接到互联网

ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = manager.getActiveNetworkInfo();
boolean hasConnect = (i!= null && i.isConnected() && i.isAvailable());

if(hasConnect)
                    {
                       // show the webview
                    }
else
 {
    // do what ever you need when when no internet connection
 }

用户转到 webview 后,如果连接丢失,您可以从以下代码中捕获该事件

 webView.setWebViewClient(new Callback());

 public class Callback extends WebViewClient{
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
        Toast.makeText(getApplicationContext(), "Failed loading app!, No Internet Connection found.", Toast.LENGTH_SHORT).show();


    }
}  

以下权限需要给予

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

于 2017-10-15T02:37:44.940 回答
0

您需要覆盖WebViewClient的shouldOverrideUrlLoading方法以捕获 URL 点击。

要检查 Wifi 状态,您需要使用ConnectivityManager

尝试这个:

WebView mWebView;
NetworkInfo networkInfoWifi = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_WIFI);

mWebView.setWebViewClient(mWebClient);

WebViewClient mWebClient = new WebViewClient(){

    @Override
    public boolean shouldOverrideUrlLoading(WebView  view, String  url){
        return true;
    }

    @Override
    public void onLoadResource(WebView  view, String  url){
        if (networkInfoWifi.isConnected()) {
            //Take action
        }
    }

}

我建议将您的问题分成两个较小的步骤 - 单击拦截和连接状态检查,然后搜索它们。这会产生很多结果,我能够使用这两个现有的答案来组合代码:

拦截 Webview 点击

检查 Wifi 连接

于 2013-07-31T00:28:04.787 回答