在Webview中使用“不再显示”复选框的Android Alert

时间:2017-04-15 05:45:29

标签: javascript android checkbox webview sharedpreferences

我有一个Web视图在点击帮助JavaScript界面​​时它将打开我的Android活动来自web-view这里工作正常...

所以这里当用户点击任何JS-Interface按钮时......我添加了一个警告

所以,当用户点击它时......它会显示一个对话框......

现在我跟着this添加了一个选项,比如不要再问......复选框

这里我给了共享首选项和复选框...但它不起作用......

还有一个复选框在网络视图中是可行的...它应该仅在警报时显示..但它显示所有时间......

任何人都可以建议我..如何使用复选框显示警报..不要再在android Webview中询问...并记住复选框...

java.lang.RuntimeException: Unable to start activity ComponentInfo{Mypackage/myactivity}: android.view.InflateException: Binary XML file line #18: Error inflating class checkbox

更新

以下是my code,我已在警报中添加了example code ...

实际上我需要一个没有XML for Checkbox的复选框...(由于XML for Check复选框,我的主Web视图出现了一些错误) 是否可能..如果是这样,请让我知道......

1 个答案:

答案 0 :(得分:2)

我打算将你的问题分解为两部分

1)显示对话框并记住用户是否选择不再显示

带有共享偏好设置的简单警报对话框可以做到这一点。

   private void handleAlertDialog() {
    //Handle showAlert
    //check if allow to show dialog
    if (!getSharedPreferences("MyPrefsFile1", MODE_PRIVATE)
            .getBoolean("ShowDialog", false)) {

        final CharSequence[] items = {"Would like to Remember this setting ? "};

        AlertDialog dialog = new AlertDialog.Builder(WebViewActivity.this)
                .setTitle("Allow location access")
                .setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
                        if (isChecked) {
                            //If the user checked the item, add it to the selected items
                            // Don't Allow, remember


                            getSharedPreferences("MyPrefsFile1", MODE_PRIVATE)
                                    .edit()
                                    .putBoolean("ShowDialog", true).commit();

                            Toast.makeText(getApplicationContext(), "Remember", Toast.LENGTH_SHORT).show();
                        } else {


                            getSharedPreferences("MyPrefsFile1", MODE_PRIVATE)
                                    .edit()
                                    .putBoolean("ShowDialog", false).commit();

                            Toast.makeText(getApplicationContext(), "Don't Remember", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        //  Your code when user clicked on OK
                        //  You can write the code  to save the selected item here
                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        //  Your code when user clicked on Cancel
                    }
                }).create();
        dialog.show();
    }
}

2)从javascript中触发此方法。

在Android N显示您还需要覆盖shouldOverrideUrlLoading(WebView view, String url)后,

shouldOverrideUrlLoading(WebView view, WebResourceRequest request)已被弃用。

完整的WebViewClient类将如下所示。

    /**
    * WebViewClient subclass loads all hyperlinks in the existing WebView
     */
    public class GeoWebViewClient extends WebViewClient {

        Dialog loadingDialog = new Dialog(WebViewActivity.this);

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

            if (url.startsWith("mailto:")) {
                //Handle mail Urls
                startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)));

            } else if (url.startsWith("tel:")) {

                //Handle telephony Urls
                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));

            } else if (url.startsWith("showalert:")) {
                handleAlertDialog();

            } else {
                view.loadUrl(url);
            }
            return true;
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            final Uri uri = request.getUrl();
            if (uri.toString().startsWith("mailto:")) {

                //Handle mail Urls
                startActivity(new Intent(Intent.ACTION_SENDTO, uri));
            } else if (uri.toString().startsWith("tel:")) {

                //Handle telephony Urls
                startActivity(new Intent(Intent.ACTION_DIAL, uri));
            } else if (uri.toString().startsWith("showalert:")) {

                 //Handle Alert
                handleAlertDialog();

            } else {
                //Handle Web Urls
                view.loadUrl(uri.toString());
            }
            return true;
        }

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

isConnected方法用于检查网络连接

/**
 * 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;

}

正如您所看到的,我添加了一个过滤器,用showalert:检查网址开头。如果我的Web客户端类捕获以showalert开头的任何URL,则会触发handleAlert方法。

结果

enter image description here

2)从javascript中触发此方法。

在Android N显示您还需要覆盖shouldOverrideUrlLoading(WebView view, String url)后,

shouldOverrideUrlLoading(WebView view, WebResourceRequest request)已被弃用。

完整的WebViewClient类将如下所示。

    /**
    * WebViewClient subclass loads all hyperlinks in the existing WebView
     */
    public class GeoWebViewClient extends WebViewClient {

        Dialog loadingDialog = new Dialog(WebViewActivity.this);

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

            if (url.startsWith("mailto:")) {
                //Handle mail Urls
                startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)));

            } else if (url.startsWith("tel:")) {

                //Handle telephony Urls
                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));

            } else if (url.startsWith("showalert:")) {
                handleAlertDialog();

            } else {
                view.loadUrl(url);
            }
            return true;
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            final Uri uri = request.getUrl();
            if (uri.toString().startsWith("mailto:")) {

                //Handle mail Urls
                startActivity(new Intent(Intent.ACTION_SENDTO, uri));
            } else if (uri.toString().startsWith("tel:")) {

                //Handle telephony Urls
                startActivity(new Intent(Intent.ACTION_DIAL, uri));
            } else if (uri.toString().startsWith("showalert:")) {

                 //Handle Alert
                handleAlertDialog();

            } else {
                //Handle Web Urls
                view.loadUrl(uri.toString());
            }
            return true;
        }

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

isConnected方法用于检查网络连接

/**
 * 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;

}

正如您所看到的,我添加了一个过滤器,用showalert:检查网址开头。如果我的Web客户端类捕获以showalert开头的任何URL,则会触发handleAlert方法。

结果

enter image description here