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 mMenuItems;
    private JSInterface jsInterface;
    private static final int FILECHOOSER_RESULTCODE = 1001;
    public static final int LOGIN = 1002;
    private ValueCallback mUploadMessage;
    private ValueCallback 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 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 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 additionalHttpHeaders() {
        Map 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 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() {
                        @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() {
                        @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();
    }
}

你可能感兴趣的:(Android之webview交互)