安卓中WebView跟Js交互

来源:互联网 发布:主机与设备传送数据时 编辑:程序博客网 时间:2024/05/18 00:22

最近在写appCan支付宝插件的时候用了大量的js跟本地交互事件,在这里整理下最近的东西


首先用WebView去加载一个网页的时候,我们需要对webView进行设置,以便可以进行跟js的交互


上代码:

public class MainActivity extends AppCompatActivity {    private WebView mWebView;    private TextView text;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mWebView = (WebView) findViewById(R.id.webView);        text = (TextView) findViewById(R.id.text);        WebSettings mWebSetting = mWebView.getSettings();        mWebSetting.setJavaScriptEnabled(true);//允许运行js脚本        mWebSetting.setJavaScriptCanOpenWindowsAutomatically(true);//允许js弹窗        mWebView.setWebChromeClient(new MyClient());        /**         * params:         * Object:         * String:这个是标识,在Js上面需要用这个标识 .Activity里面的方法         *         * */        mWebView.addJavascriptInterface(this,"Activity");        mWebView.loadUrl("file:///android_asset/demo.html");    }    @JavascriptInterface->android4.2之后需要用注解来标记被网页执行的函数    public void android_method(String params) {        Toast.makeText(MainActivity.this, "js按钮的交互事件", Toast.LENGTH_SHORT).show();        mWebView.loadUrl("javascript:js_method('Activity传递的参数')");//这里可以将任何参数通过这个入口传给js页面        text.setText(params);       /*runOnUiThread(new Runnable() {           @Override           public void run() {               mWebView.loadUrl("javascript:js_method()");           }       });*/    }    class MyClient extends WebChromeClient{        @Override        public void onProgressChanged(WebView view, int newProgress) {//进度条的操作            super.onProgressChanged(view, newProgress);        }        /**         * Tell the client to display a javascript alert dialog.  If the client         * returns true, WebView will assume that the client will handle the         * dialog.  If the client returns false, it will continue execution.         * @param view The WebView that initiated the callback.         * @param url The url of the page requesting the dialog.         * @param message Message to be displayed in the window.         * @param result A JsResult to confirm that the user hit enter.         * @return boolean Whether the client will handle the alert dialog.         */        @Override        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {            Log.e("TAG","message:"+message);            result.confirm();//完成            return false;        }    }}
布局代码

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:weightSum="1">    <WebView        android:id="@+id/webView"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_weight="1"></WebView>    <TextView        android:id="@+id/text"        android:gravity="center"        android:layout_width="match_parent"        android:layout_height="50dp"         /></LinearLayout>

1,获取webSettings设置JavaScriptEnabled为true

2,允许js弹窗 

setJavaScriptCanOpenWindowsAutomatically(true)
3,调用本地浏览网页

4,添加js接口(本地需要跟js交互的方法,本地什么方法跟js交互?方法名注解为@javaScriptInterface,本文中用到的是android_method

/**         * params:         * Object:         * String:这个是标识,在Js上面需要用这个标识 .Activity里面的方法         *         * */        mWebView.addJavascriptInterface(this,"Activity");</span></span></span>

下面贴上js代码

<html>    <head>    <script type="text/javascript">        /* This function is invoked by the activity */        function js_method(params) {            alert(params);        }    </script>    <body>    <font color="red" size="20px">这是一个js页面</font>        <input type="button" onclick="Activity.android_method('js传递的值')" value="js页面的按钮">    </body>    </head></html>

流程解释;


首先当页面加载起来之后,点击js页面的按钮-->这时候会去调用Activity(这是标识).android_method(本地方法)

-->本地会有一个toast弹窗然后执行js页面的方法

javascript:js_method('Activity传递的参数')-->js页面会将这个带来的参数alert()
最后本地的textView值变成了从js页面传递过来的值 ..运行结果





2 0