Android之webview交互

封装好的BrowserActivity

@Route(path = Constants.RouteUrl.CORE_BROWSER)
public class BrowserActivity extends TitleActivity {

    private static final int REQUEST_LOGIN = 1;
    @Autowired(name = "url")
    public String url;
    private JsMenu mJsMenu;
    private boolean mShoucang;
    private String mArticleId;
    private int mArticleType;

    public String getUrl() {
        url = getIntent().getStringExtra("url");
        return url;
    }

    private static final String WEB_ERROR_URL = "file:///android_asset/webkit/error.html";
    private static final String WEB_TITLE = "title";
    private static final String WEB_WEBSITE = "url";
    private static final String IMAGE_FILE_NAME = "browser.jpg";
    private File mCameraFile;
    WebView webView;
    LinearLayout tipLayout;
    RelativeLayout tipIconLayout;
    TextView tipDesc;
    Button optionBtn;
    ProgressBar progressBar;
    WebSettings settings;
    String mTitleLoading = "加载中...";
    String mTitle;
    List<WebMenu> mMenuItems;
    private JSInterface jsInterface;
    private static final int FILECHOOSER_RESULTCODE = 1001;
    public static final int LOGIN = 1002;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mValueCallback;
    private int selectImgMax = 1;//选取图片最大数量

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setNeedLogin(false);
        //三星手机硬件加速关闭后导致H5弹出的对话框出现不消失情况
        String brand = Build.BRAND;
        if ("samsung".equalsIgnoreCase(brand) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        }
        super.onCreate(savedInstanceState);
        setBrowserTitle("");
        setContentView(R.layout.base_activity_browser);
        mCameraFile = new File(getExternalDir(), IMAGE_FILE_NAME);
        tipIconLayout = (RelativeLayout) findViewById(R.id.tip_icon_layout);
        tipLayout = (LinearLayout) findViewById(R.id.tip_layout);
        waveView = (WaveView) findViewById(R.id.tip_icon);
        waveView.setShapeType(WaveView.ShapeType.CIRCLE);
        waveView.setWaveColor(
                Color.parseColor("#ff9c9c"),
                Color.parseColor("#ff5c5c"));
        tipDesc = (TextView) findViewById(R.id.tip_desc);
        optionBtn = (Button) findViewById(R.id.option_btn);
        webView = (WebView) findViewById(R.id.webView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        jsInterface = new JSInterface(this, webView);
        showTipIcon();
        initData();
        initWebViewSettings();
    }


    public File getExternalDir() {
        File file = FileKit.getStorageDir(this);
        return file;
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent.hasExtra(WEB_TITLE)) {
            mTitle = intent.getStringExtra(WEB_TITLE);
            if (!TextUtils.isEmpty(mTitle)) {
                setBrowserTitle(mTitle);
            } else {
                setBrowserTitle(mTitleLoading);
            }
        }
//        url = intent.getStringExtra(WEB_WEBSITE);
//        if (TextUtils.isEmpty(url)) {
//            url = DEFAULT_URL;
//        }
    }

    //    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void initWebViewSettings() {
        settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setSupportZoom(true);//支持缩放
        settings.setBuiltInZoomControls(true);//支持手势缩放
        settings.setDisplayZoomControls(false); //是否显示缩放按钮
        settings.setSaveFormData(true);
        settings.setAllowFileAccess(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setAppCacheEnabled(true);

        settings.setAppCachePath(getCacheDir().getPath());
        settings.setAppCacheMaxSize(Integer.MAX_VALUE);
        settings.setDefaultTextEncodingName("UTF-8");
        //屏幕自适应
        settings.setUseWideViewPort(true);//设置页面自适应手机屏幕;将图片调整到适合WebView的大小
        settings.setLoadWithOverviewMode(true);//自适应屏幕

        settings.setSaveFormData(false);
        settings.setSavePassword(false);
        settings.setBlockNetworkImage(false);//解决图片不显示

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);//优先使用缓存
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            settings.setDisplayZoomControls(false);
        }

        // >= 19(SDK4.4)启动硬件加速,否则启动软件加速
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && shouldOpenHardware()) {
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            settings.setLoadsImagesAutomatically(true);//支持自动加载图片
        } else {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            settings.setLoadsImagesAutomatically(false);
        }

        if (Build.VERSION.SDK_INT > 11) {
            webView.removeJavascriptInterface("searchBoxJavaBridge_");
            webView.removeJavascriptInterface("accessibility");
            webView.removeJavascriptInterface("accessibilityTraversal");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && AppConfig.DEBUG_MODE) {
            webView.setWebContentsDebuggingEnabled(true);
        }
        //解决加载https图片不显示的问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.addJavascriptInterface(jsInterface, JSInterface.INTERFACE_NAME);


        webView.setHorizontalFadingEdgeEnabled(false);
        webView.setVerticalFadingEdgeEnabled(false);
        webView.setHorizontalScrollbarOverlay(true);
        webView.setHorizontalScrollBarEnabled(false);
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER); // 取消WebView中滚动或拖动到顶部、底部时的阴影
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // 取消滚动条白边效果
        webView.requestFocus();

        //不同设备点击WebView输入框键盘的不弹起
        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                try {
                    if (webView != null)
                        webView.requestFocus();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
        });
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log4a.i("open URL>>>>>" + url);
                if (url.startsWith("mailto:") ||
                        url.startsWith("tel:") ||
                        url.startsWith("sms:") ||
                        url.startsWith("mqqwpa:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log4a.i("open URL new>>>>>" + getUrl());
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
                Log4a.i(url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                try {
                    super.onPageFinished(view, url);
                    webView.setLayerType(View.LAYER_TYPE_NONE, null);
                    progressBar.setVisibility(View.GONE);
                    if (!settings.getLoadsImagesAutomatically()) {
                        settings.setLoadsImagesAutomatically(true);
                    }
                } catch (Exception e) {
                    Log4a.d(e);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                final SslErrorHandler mHandler;
                mHandler = handler;
                AlertDialog.Builder builder = new AlertDialog.Builder(BrowserActivity.this);
                builder.setMessage("ssl证书验证失败");
                builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mHandler.proceed();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mHandler.cancel();
                    }
                });
                builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                            mHandler.cancel();
                            dialog.dismiss();
                            return true;
                        }
                        return false;
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
//                把出错的WebView内容清除
                view.loadDataWithBaseURL(null, "", "text/html", "UTF-8", null);
//                view.setVisibility(View.GONE);
                view.loadUrl(WEB_ERROR_URL);
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                view.loadUrl(WEB_ERROR_URL);
                progressBar.setVisibility(View.GONE);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {

            // For Android 5.0+
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
                mValueCallback = valueCallback;
                selectImgMax = selectImgMax > 1 ? selectImgMax : 1;
                goToPhotos();
                return true;
            }


            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg) {
                mUploadMessage = uploadMsg;
                selectImgMax = 1;
                goToPhotos();
            }

            //3.0--版本
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                openFileChooser(uploadMsg);
            }

            // For Android 4.1
            public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
                openFileChooser(uploadMsg);
            }

            private void goToPhotos() {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri uriForFile = FileProvider.getUriForFile(BrowserActivity.this, AppConfig.PACKAGE_NAME + ".fileprovider", mCameraFile);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uriForFile);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                }
                startActivityForResult(Intent.createChooser(intent, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                //默认处理了,没必要弹出一个框框
                callback.invoke(origin, true, false);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress >= 100) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    if (progressBar.getVisibility() == View.GONE) {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                    progressBar.setProgress(newProgress);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, final String title) {
                super.onReceivedTitle(view, title);
                if (TextUtils.isEmpty(mTitle)) { //过滤Title显示网页
                    setBrowserTitle(title);
                }
            }
        });

        initCookie();
        webView.loadUrl(getUrl(), additionalHttpHeaders());
    }

    public void setBrowserTitle(String title) {
        if (TextUtils.isEmpty(title)) {
            setTitle("");
            return;
        }
        if (title.equals("#hide#")) {
            setTitle("");
            return;
        }
        if (title.startsWith("http")) {
            setTitle("");
            return;
        }
        setTitle(title);
    }

    private void initCookie() {
        CookieSyncManager.createInstance(this);
        CookieManager instance = CookieManager.getInstance();
        instance.setAcceptCookie(true);
        Uri uri = Uri.parse(getUrl());
        String host = uri.getHost();

        Map<String, String> cookie = WebStore.me().getCookies();
        if (!TextUtils.isEmpty(host) && !cookie.isEmpty()) {

            for (String key : cookie.keySet()) {
                instance.setCookie(host, key + "=" + cookie.get(key));
                Log4a.d(String.format("cookie: %s = %s", key, cookie.get(key)));
            }

            instance.setCookie(host, "path=/");
            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
            instance.setCookie(host, "width=" + displayMetrics.widthPixels);

            instance.setCookie(host, "height=" + displayMetrics.heightPixels);
            instance.setCookie(host, "device=android");
            instance.setCookie(host, "rrh_version=" + AppConfig.VERSION_NAME);
        }
    }

    private Map<String, String> additionalHttpHeaders() {
        Map<String, String> additionalHttpHeaders = new HashMap<>();
        String token = CacheService.getInstance().getToken();
        if (!TextUtils.isEmpty(token)) {
            additionalHttpHeaders.put("Authorization", "Bearer " + token);
            additionalHttpHeaders.put("Cache-Control", "no-cache");
            additionalHttpHeaders.put("Version", String.valueOf(AppConfig.VERSION_NAME));
        }
        return additionalHttpHeaders;
    }

    /**
     * 设置菜单
     *
     * @param menus
     */
    public void setMenuItem(@NonNull List<WebMenu> menus) {
        if (mMenuItems == null) {
            mMenuItems = new ArrayList<>();
        }
        mMenuItems.clear();
        mMenuItems.addAll(menus);
        invalidateOptionsMenu();
    }

    public ProgressBar getProgressBar() {
        return progressBar;
    }

    public WebView getWebView() {
        return webView;
    }

    public void setTipLayoutVisibility(int visibility) {
        tipLayout.setVisibility(visibility);
    }


    //    private Drawable mDrawable;
    private WaveView waveView;
    WaveHelper mWaveHelper;

    public void showTipIcon() {
        try {
            if (mWaveHelper == null)
                mWaveHelper = new WaveHelper(waveView);
//        if (mDrawable instanceof Animatable) {
//            if (!((Animatable) mDrawable).isRunning()) {
//                ((Animatable) mDrawable).start();
//            }
//        }
            mWaveHelper.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        setTipIconVisibility(View.VISIBLE);
    }

    public void hiddTipIcon() {
        try {
            if (mWaveHelper != null) {
                mWaveHelper.cancel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        setTipIconVisibility(View.GONE);
    }

    public void setTipIconVisibility(int visibility) {
        tipIconLayout.setVisibility(visibility);
    }

    public void setTipDesc(String text) {
        tipDesc.setText(text);
        setTipDescVisibility(View.VISIBLE);
    }

    public void setTipDescVisibility(int visibility) {
        tipDesc.setVisibility(visibility);
    }

    public void setOptionBtn(String text, View.OnClickListener listener) {
        optionBtn.setText(text);
        optionBtn.setOnClickListener(listener);
        setOptionBtnVisibility(View.VISIBLE);
    }

    public void setOptionBtnVisibility(int visibility) {
        optionBtn.setVisibility(visibility);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LOGIN) {
            if (CacheService.getInstance().isLogin()) {
                updateShoucangIcon();
            }
        } else {
            ShareHelper.getInstance(this).shareOnActivityResult(requestCode, resultCode, data);
            jsInterface.onActivityResult(requestCode, resultCode, data);
            if (requestCode == FILECHOOSER_RESULTCODE && null != data) {
            }
        }
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        if (mMenuItems == null && mJsMenu == null) return true;

        if (mMenuItems != null) {
            for (int intent = 0; intent < mMenuItems.size(); intent++) {
                final WebMenu item = mMenuItems.get(intent);
                final MenuItem subItem = menu.add(0, intent, item.order, item.title);
                subItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
            }
        }

        if (mJsMenu != null) {
            for (int intent = 0; intent < mJsMenu.navTitles.size(); intent++) {
                final JsMenu.NavTitlesBean item = mJsMenu.navTitles.get(intent);
                if (item.type == 1) {
                    //收藏功能
                    setBrowserTitle("");
                    MenuInflater menuInflater = getMenuInflater();
                    if (mShoucang) {
                        menuInflater.inflate(R.menu.menu_base_star, menu);
                    } else {
                        menuInflater.inflate(R.menu.menu_base_unstar, menu);
                    }
                    updateShoucangIcon();
                } else if (item.type == 2) {
                    //分享功能
                    MenuInflater menuInflater = getMenuInflater();
                    menuInflater.inflate(R.menu.menu_base_share, menu);
                }
            }
        }

        return true;
    }

    /**
     * 特殊处理,有收藏功能的文章,获取文章是否被收藏
     */
    private void updateShoucangIcon() {
        if (CacheService.getInstance().isLogin()) {
            for (final JsMenu.NavTitlesBean menuBean : mJsMenu.navTitles) {
                if ((menuBean.type == 1) && !TextUtils.isEmpty(menuBean.articleid)) {
                    mArticleId = menuBean.articleid;
                    mArticleType = menuBean.articletype;
                    DataRepository.getInstance().hasUpdateCollect(mArticleType, mArticleId, new Callback<ArticleHasCollection>() {
                        @Override
                        public void onResponse(ArticleHasCollection response, boolean fromCache) {
                            if (mShoucang != response.result) {
                                mShoucang = response.result;
                                invalidateOptionsMenu();
                            }
                        }
                    });
                    break;
                }
            }
        }
    }

    int tag = 0;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        } else if (id == R.id.menu_common_share) {

            //防止用户点击过快,出现两次分享

            if (!ButtonUtils.isFastDoubleClick(R.id.menu_common_share, 2000)) {
                String title = "";
                String desc = "";
                String link = "";
                String imgUrl = "";
                try {
                    for (JsMenu.NavTitlesBean menuBean : mJsMenu.navTitles) {
                        if (menuBean.type == 2 && menuBean.sharedata != null) {
                            title = menuBean.sharedata.title;
                            desc = menuBean.sharedata.des;
                            imgUrl = menuBean.sharedata.img;
                            link = java.net.URLDecoder.decode(menuBean.sharedata.url, "UTF-8");
                        }
                    }
                    //分享功能
                    showShare(title, desc, link, imgUrl);
                } catch (Exception e) {
                    showToast("分享暂时不可用");
                }
            }

        } else if (id == R.id.common_shoucang_unclicked || id == R.id.common_shoucang_clicked) {
            if (CacheService.getInstance().isLogin()) {
                tag = tag == 0 ? 1 : 0;
                if (!TextUtils.isEmpty(mArticleId)) {
                    DataRepository.getInstance().collectSource(mArticleType, mArticleId, new Callback<CollectResult>() {
                        @Override
                        public void onResponse(CollectResult response, boolean fromCache) {
                            if (response.status != CollectResult.ERROR) {
                                updateShoucangIcon();
                            }
                        }
                    });
                }
            } else {
                RouteDispathActivity.route(this, Constants.RouteUrl.USER_LOGIN, REQUEST_LOGIN);
            }
            //分享功能
        } else {
            if (mMenuItems != null && id >= 0 && mMenuItems.size() > id) {
                WebMenu webItem = mMenuItems.get(id);
                String action = webItem.action;
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    public void showShare(String title, String desc, String link, String imgUrl) {

        ShareHelper.getInstance(this).openShare(link, title, desc, imgUrl, new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                showToast("分享成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                Log4a.e(throwable.getMessage());
                if (throwable != null && throwable.getMessage() != null && throwable.getMessage().contains("没有安装应用")) {
                    showToast("没有安装相关应用");
                } else {
                    showToast("分享失败了");
                }
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                showToast("分享取消");
            }
        });
    }

    /**
     * 不同版本硬件加速的问题
     *
     * @return
     */
    public static boolean shouldOpenHardware() {
        if ("samsung".equalsIgnoreCase(Build.BRAND))
            return false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            return true;
        return true;
    }

    private void destroyWebView() {
        if (webView == null)
            return;
        try {
            webView.stopLoading();
            webView.clearHistory();
//            webView.clearCache(true);
            webView.clearFormData();
            ViewParent viewParent = webView.getParent();
            if (viewParent != null && viewParent instanceof ViewGroup)
                ((ViewGroup) viewParent).removeView(webView);
            webView.removeAllViews();
            webView.destroy();
            webView = null;
        } catch (Exception e) {
            Log4a.d(e);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyWebView();
        try {
            CookieManager.getInstance().removeAllCookie();
            try {
                if (mWaveHelper != null) {
                    mWaveHelper.cancel();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (mMenuItems != null) mMenuItems.clear();
        } catch (Exception e) {
            Log4a.d(e);
        }
    }

    @Override
    public void onBackPressed() {
        if (webView == null)
            return;

        //js交互使用到的

        //这是点击左上角的箭头返回 type: 0 一页一页返回  1直接返回到native关闭我所有h5页面 2 返回到指定的url页面  默认0(只有2的时候才判断url,0,1的时候url传空‘’)

        if (mBackType == 1) {
            finish();
            return;
        } else if (mBackType == 2) {
            if (!TextUtils.isEmpty(mBackUrl)) {
                RouteDispathActivity.route(this, mBackUrl);
            }
            return;
        }

        if (TextUtils.isEmpty(url) || url.contains("/userVerify/sesame?jump_type=1")) {
            finish();
            return;
        }
        WebBackForwardList backForwardList = webView.copyBackForwardList();
        if (backForwardList != null && backForwardList.getSize() != 0) {
            int currentIndex = backForwardList.getCurrentIndex();
            WebHistoryItem historyItem = backForwardList.getItemAtIndex(currentIndex);
            if (historyItem != null) {
                String backPageUrl = historyItem.getUrl();
                if (TextUtils.isEmpty(backPageUrl))
                    return;
                if (backPageUrl.contains("android_asset/webkit/error.html")) {
                    finish();
                    return;
                }
            }
        }
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private int mBackType = -1;//默认值-1
    private String mBackUrl = "";

    public void setBackControl(int type, String url) {
        mBackType = type;
        mBackUrl = url;
    }

    public void showAreaDialog(final String callid, final JSInterface.IAreaListener iAreaListener) {
        final AreaDialog areaDialog = new AreaDialog();
        Bundle args = new Bundle();
        args.putInt("col", 3);
        areaDialog.setArguments(args);
        areaDialog.setOnAreaChangedListener(new AreaDialog.OnAreaChangedListener() {
            @Override
            public void onAreaChanged(String province, String city, String county, int provinceCode, int cityCode, int countyCode) {

            }
        });
        areaDialog.setAreaListener(new AreaDialog.AreaListener() {

            public void OnOkClicked() {
                Province province = areaDialog.getProvince();
                String provinceStr = "";
                String where1 = "";
                if (province != null) {
                    where1 = province.getName();
                    provinceStr = province.getName();
                }
                City city = areaDialog.getCity();
                if (city != null) {
                    if ("市辖区".equals(city.getName()) || "县".equals(city.getName())) {
                        where1 += provinceStr;
                    } else {
                        where1 += city.getName();
                    }
                }

                County country = areaDialog.getCountry();
                if (country != null) {
                    if ("市辖区".equals(country.getName()) || "县".equals(country.getName())) {
                        where1 += "";
                    } else {
                        where1 += country.getName();
                    }
                }
                iAreaListener.onSelect(callid, where1);

            }
        });
        if (!areaDialog.isVisible()) {
            areaDialog.show(getSupportFragmentManager(), "area");
        }
    }

    public void setJsMenu(JsMenu jsMenu) {
        mJsMenu = jsMenu;
        invalidateOptionsMenu();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 197,099评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,846评论 2 374
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 144,146评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,789评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,656评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,467评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,870评论 3 389
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,500评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,790评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,828评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,628评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,449评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,881评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,077评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,376评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,879评论 2 343
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,089评论 2 338

推荐阅读更多精彩内容