Android客户端WebView与JavaScript之间的交互

最近公司的APP老板老是改需求又嫌更新版本慢,然后页面慢慢转成用H5了。

采用WebView来加载页面,经常需要客户端和JS互相调用,进行数据传递,页面跳转什么的。

在这里记录一下项目中用到的


/** * Created by CC on 2016/10/28. */public class MyMainActivity extends Activity {    private Dialog loadingDialog;    private WebView mWebView;    private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.layout_main);        initWebView();        initView();    }    private void initWebView() {        mWebView = (WebView) findViewById(R.id.wv);        mWebView.loadUrl("your url");        setWebView(mWebView,client,chromeClient);        //JS调用客户端的方法        //这里JsCallWebAndroid类里面的方法名,和第二个参数都要跟JS那边对应        mWebView.addJavascriptInterface(new JsCallWebAndroid(this),"index");    }    private void initView() {        button = (Button) findViewById(R.id.bt);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //客户端调用JS的方法,传参和不传参两种                mWebView.loadUrl("javascript:recordCallback()");//                mWebView.loadUrl("javascript:recordCallback('" + new File(path) + "')");            }        });    }    /**     * 设置参数     * @param webView     * @param client     * @param chromeClient     */    private void setWebView(WebView webView, WebViewClient client, WebChromeClient            chromeClient){        webView.setWebViewClient(client);        webView.setWebChromeClient(chromeClient);        WebSettings settings = webView.getSettings();        settings.setJavaScriptEnabled(true);       //设置支持javascript脚本        settings.setSupportZoom(true);             // 支持缩放        String ua = settings.getUserAgentString();//        settings.setUserAgentString();        //为了便于WEB端统计分析        if(!BuildConfig.LOG_DEBUG){            if(isOpenNetwork()){                settings.setCacheMode(settings.LOAD_DEFAULT);                return;            }            settings.setCacheMode(settings.LOAD_CACHE_ELSE_NETWORK);        }else{            webView.setWebContentsDebuggingEnabled(true);        }    }    private WebChromeClient chromeClient = new WebChromeClient(){        @Override        public void onProgressChanged(WebView view, int newProgress) {            // super.onProgressChanged(view, newProgress);        }        @Override        public void onReceivedTitle(WebView view, String title) {            super.onReceivedTitle(view, title);        }    };    /**     * 有时网络慢,为了让用户看见页面其实是有个加载过程的,     * 这里添加了一个加载页面的dialog, 在页面开始加载时显示,页面加载完后消失     */    private WebViewClient client = new WebViewClient(){        @Override        public void onPageStarted(WebView view, String url, Bitmap favicon) {            super.onPageStarted(view, url, favicon);            loadingDialog.show();        }        @Override        public boolean shouldOverrideUrlLoading(WebView view, String url) {            view.loadUrl(url);            return true;        }        @Override        public void onPageFinished(WebView view, String url) {            super.onPageFinished(view, url);            loadingDialog.dismiss();        }        @Override        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError                error) {            super.onReceivedError(view, request, error);            loadingDialog.dismiss();        }    };    private boolean isOpenNetwork() {        ConnectivityManager connManager = (ConnectivityManager)Global.getContext().getSystemService(Context                .CONNECTIVITY_SERVICE);        if(connManager.getActiveNetworkInfo() != null) {            return connManager.getActiveNetworkInfo().isAvailable();        }        return false;    }

evaluateJavascript()用于异步调用JavaScript方法,并且返回数据。

mWebView.evaluateJavascript(script, new ValueCallback() {     @Override     public void onReceiveValue(String value) {          //TODO     }});


JS调用客户端里 的方法, 客户端在此类对应方法里做自己所需要实现功能的处理


public class JsCallWebAndroid {        private Activity mActivity;        public JsCallWebAndroid(Activity activity) {            this.mActivity = activity;        }        @JavascriptInterface        public void goToGroupChat(final String groupId) {            new Handler().post(new Runnable() {                @Override                public void run() {                    mActivity.startActivity(new Intent(mActivity, ToGroupActivity.class).putExtra("group_id", groupId));                }            });        }    }