Android如何在单击WebView内的按钮时显示没有互联网错误

时间:2015-12-01 13:42:56

标签: android webview

我正在使用WebView开发Android应用程序。在那个WebView中我有一个按钮。当我点击该按钮并且没有可用的互联网时,我需要显示错误消息。但我无法做到这一点。有人有想法吗?任何帮助将受到高度赞赏。以下是我的代码。

@SuppressLint("SetJavaScriptEnabled")
public class DashboardFragment extends Fragment implements SolutionHandler {
    private final String SAVE_DASHBOARD_PAGE = "saveDashboardPage";
    private final String SAVE_DASHBOARD_WEB_STATE = "saveDashboardWebState";

    private final String DASHBOARD_URL = "https://api.myapp.com/api_endpoint/dashboard/";
    private final String LOGOUT_URL = "myapp://logout/";
    private final String SOLUTION_URL = "myapp://solution/open?solution_id";
    private final String MY_APP = "myapp://";
    private final String SUPPORT_URL = "http://support";

    private View dashboardView;
    private WebView dashboardWebView;

    private String currentUrl;
    private User user;

    private LoadingDialog loadingDialog;

    private Bundle webState;

    private int supportUrlAcessCount = 0;


    public DashboardFragment() {
         setRetainInstance(true);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        OptimizeHIT.sendScreen(GAnalyticsScreenNames.DASHBOARD_SCREEN, null, null);

        dashboardView = inflater.inflate(R.layout.fragment_dashboard, container, false);

        user = User.sharedUser(getActivity());




        if (savedInstanceState != null) {
            currentUrl = savedInstanceState.getString(SAVE_DASHBOARD_PAGE);
            webState = savedInstanceState.getBundle(SAVE_DASHBOARD_WEB_STATE);
        }

        if (currentUrl == null || currentUrl.length() == 0) {
            currentUrl = DASHBOARD_URL + user.hash();
        }

        loadingDialog = new LoadingDialog(getActivity(), R.string.loading_dashboard, R.string.icon_arrows_cw, true);
        WebChromeClient webClient = new WebChromeClient();

        if (dashboardWebView == null) {
            dashboardWebView = new WebView(getActivity());
            dashboardWebView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

            dashboardWebView.setVerticalScrollBarEnabled(true);
            dashboardWebView.setHorizontalScrollBarEnabled(true);
            dashboardWebView.requestFocusFromTouch();
            dashboardWebView.getSettings().setAppCachePath(getActivity().getCacheDir().getAbsolutePath());
            dashboardWebView.getSettings().setAppCacheEnabled(true);
            dashboardWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);


//          dashboardWebView.setOnTouchListener(webViewTouchListener);

            dashboardWebView.setWebChromeClient(webClient);
            dashboardWebView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    // TODO Auto-generated method stub


                    if(!isNetworkAvailable(getActivity())){
                        showNoInternetError();
                    }
                    super.onPageStarted(view, url, favicon);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    if (url.startsWith(DASHBOARD_URL)) {
                        view.clearHistory();
                        loadingDialog.dismiss();
                    }
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {

                        if (url != null && url.startsWith(OHITAPP)) {
                            if (url.startsWith(SOLUTION_URL)) {
                                loadingDialog.setStringResource(R.string.loading_solution);
                                loadingDialog.show();

                                Locker.lock(getActivity());

                                Pattern pattern = Pattern.compile("[0-9]+");
                                Matcher matcher = pattern.matcher(url);

                                String solutionId = "";

                                if (matcher.find()) {
                                    solutionId = matcher.group();
                                }



                            }

                            return true;
                        } else if (url.startsWith(SUPPORT_URL)) {
                            supportUrlAcessCount++;
                            if (supportUrlAcessCount == 2) {
                                ((MenuActivity) getActivity()).changeFragment(6, false, false, false, null, null);

                                return true;
                            }

                            return false;
                        } else {
                            return false;
                        }

                }


                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    if ((failingUrl.startsWith(SUPPORT_URL) && supportUrlAcessCount == 2)
                            || failingUrl.startsWith(OHITAPP)) {
                        return;
                    }

                    showNoInternetError();
                }
            });

            if (webState == null) {
                if (CheckConnectionHelper.isNetworkAvailable(getActivity())) {
                    loadingDialog.show();
                    dashboardWebView.loadUrl(currentUrl);
                } else {
                    ErrorHelper.showError(TalkersConstants.JUST_FAILURE, (SuperActivity) getActivity());
                    dashboardWebView.loadUrl("about:blank");
                }


                dashboardWebView.getSettings().setSupportZoom(true);
                dashboardWebView.getSettings().setBuiltInZoomControls(true);
                dashboardWebView.getSettings().setDisplayZoomControls(false);
                dashboardWebView.getSettings().setLoadWithOverviewMode(true);
                dashboardWebView.getSettings().setUseWideViewPort(true);
                dashboardWebView.getSettings().setJavaScriptEnabled(true);
            } else {
                dashboardWebView.restoreState(webState);
            }
        } else {
            if (webState == null) {
                loadingDialog.show();
                dashboardWebView.loadUrl(currentUrl);

                dashboardWebView.getSettings().setSupportZoom(true);
                dashboardWebView.getSettings().setBuiltInZoomControls(true);
                dashboardWebView.getSettings().setDisplayZoomControls(false);
                dashboardWebView.getSettings().setLoadWithOverviewMode(true);
                dashboardWebView.getSettings().setUseWideViewPort(true);
                dashboardWebView.getSettings().setJavaScriptEnabled(true);
            } else {
                dashboardWebView.restoreState(webState);
            }
        }

        LinearLayout dashboardContainer = (LinearLayout) dashboardView.findViewById(R.id.dashboard_container);
        dashboardContainer.addView(dashboardWebView);

        getActivity().getWindow().getDecorView().getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        dashboardView.requestLayout();
                    }
                });

        return dashboardView;
    }

    @Override
    public void onDestroyView() {
        LinearLayout dashboardContainer = (LinearLayout) dashboardView.findViewById(R.id.dashboard_container);
        dashboardContainer.removeView(dashboardWebView);

        super.onDestroyView();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(SAVE_DASHBOARD_PAGE, getCurrentPage());
        outState.putBundle(SAVE_DASHBOARD_WEB_STATE, getCurrentWebViewState());

        super.onSaveInstanceState(outState);
    }

    public String getCurrentPage() {
        return dashboardWebView.getUrl();
    }

    public Bundle getCurrentWebViewState() {
        Bundle outState = new Bundle();
        dashboardWebView.saveState(outState);

        return outState;
    }



    public boolean navigatesBack() {
        if (dashboardWebView != null && dashboardWebView.canGoBack()) {
            dashboardWebView.goBack();

            return true;
        }

        return false;
    }

    public void showNoInternetError() {
        loadingDialog.dismiss();
        ErrorHelper.showError(TalkersConstants.JUST_FAILURE, (SuperActivity) getActivity());
        dashboardWebView.loadUrl("about:blank");
    }

    public void reloadWebView() {
        if (dashboardWebView.getUrl() == null
                || dashboardWebView.getUrl().isEmpty()
                || dashboardWebView.getUrl().equals("about:blank")) {
            dashboardWebView.loadUrl(currentUrl);
        }
    }

    OnTouchListener webViewTouchListener = new OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if (System.currentTimeMillis() - SuperActivity.savedLastClickTime < 1000) {
                Log.d("I AM IN A FALSE", "FALSE");
                return true;
            }

            SuperActivity.savedLastWebViewInteractionTime = System.currentTimeMillis();

            Log.d("I AM IN A TOUCH LISTENER", "TOUCH LISTENER");
            return false;
        }
    };



    public boolean isNetworkAvailable( Context context ) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

}

2 个答案:

答案 0 :(得分:0)

创建一个公共类ConnectionDetector

public class ConnectionDetector {
    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }
}

之后在您的活动或片段中初始化这些变量

    ConnectionDetector cd;
    Boolean isInternetPresent = false;

在调用webView之前,只需检查这样的连接

        cd = new ConnectionDetector(context);
                    isInternetPresent = cd.isConnectingToInternet();
                    keyBoardHide();
                    if (isInternetPresent) {
                        //call webview here
                    } else {
                        // Use Toast to popup msg
                    }

答案 1 :(得分:0)

这是类比问题。您可以检查网络是否已打开,如果不是,则可以显示错误消息。

Detect whether there is an Internet connection available on Android

相关问题