Android開發之WebView與js的資料傳遞

來源:互聯網
上載者:User

標籤:android   js   webview   webview和javascrpt的互動   

    在Android開發中不可避免的會出現,使用一個WebView來顯示一個h5頁面。如果僅僅只是顯示h5頁面,這不需要特殊的處理,但是很多情況下會出現,js和WebView的互動。比如:將html表單中的資料,傳遞到Activity中,在Activity中對資料校正,再上傳到伺服器。

    那麼js和WebView如何進行的互動的呢?

    建立AndroidHtml項目。主要代碼如下:

MainActivity.java:

    private WebView mWebView;    public static final String URL_TEST="file:///android_asset/index.html";    @SuppressLint("JavascriptInterface")    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mWebView = (WebView) findViewById(R.id.webView);        WebSettings settings = mWebView.getSettings();        settings.setJavaScriptEnabled(true);        mWebView.loadUrl(URL_TEST);        //addJavascriptInterface這個方法中有兩個參數,第一個參數是添加一個對象,這個對象中封裝了在js中要調用的native方法,第二個參數是告訴js對象的名稱以便於調用native方法        mWebView.addJavascriptInterface(this,"zzh");//    }    @JavascriptInterface//android 4.2之上的版本需要加上這個註解,表示將這個方法暴露給js調用    public void callAndroidNativeMethod(String str){        Log.d("MainActivity","---方法被執行了!!!-");        Toast.makeText(this, "---"+str, Toast.LENGTH_LONG).show();    }

註解@JavascriptInterface註解在Android版本4.2之上必須要加上。Google官方的解釋是

Caution: If you‘ve set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available to your JavaScript (the method must also be public). If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher.

index.html:

<!DOCTYPE html><HTML lang="zh-CN">    <head>        <meta charset="utf-8">        <script type="text/javascript" language="javascript">            function callAndroidNativeMethod(){                window.zzh.callAndroidNativeMethod("js中的資料傳遞到了Android中了");            }        </script>    </head>    <body>        <button onclick="callAndroidNativeMethod()">點擊調用Java代碼</button>    </body></HTML>

activity_main.xml中的布局是:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.zzh.androidhtml.MainActivity">    <Button        android:id="@+id/button"        android:text="Java調用js方法"        android:layout_width="match_parent"        android:layout_height="wrap_content"/>    <WebView        android:id="@+id/webView"        android:layout_below="@+id/button"        android:layout_width="match_parent"        android:layout_height="match_parent"></WebView></RelativeLayout>

好了,上面就是js中如何調用Android Native方法。下面來說說Android Native中怎麼調用js方法(要注意Native中調用js方法來處理Android中的商務邏輯的效率差,不建議使用此方式處理Android商務邏輯,但是也要知道如何使用)。

private WebView mWebView;public static final String URL_TEST="file:///android_asset/index.html";@SuppressLint("JavascriptInterface")@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    mWebView = (WebView) findViewById(R.id.webView);    WebSettings settings = mWebView.getSettings();    settings.setJavaScriptEnabled(true);    mWebView.loadUrl(URL_TEST);    mWebView.addJavascriptInterface(this,"zzh");    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View view) {            mWebView.loadUrl("javascript:callJavaScriptMethod()");        }    });}@JavascriptInterface//android 4.2之上的版本需要加上這個註解,表示將這個方法暴露給js調用public void callAndroidNativeMethod(String str){    Log.d("MainActivity","---方法被執行了!!!-");    Toast.makeText(this, "---"+str, Toast.LENGTH_LONG).show();}

index.html檔案比較簡單

<!DOCTYPE html><HTML lang="zh-CN"><head>    <meta charset="utf-8">    <script type="text/javascript" language="javascript">            function callAndroidNativeMethod(){                window.zzh.callAndroidNativeMethod("js中的資料傳遞到了Android中了");            }            function callJavaScriptMethod(){                document.getElementById("content").innerHTML += "<br\>java調用了js函數";            }    </script></head><body><button onclick="callAndroidNativeMethod()">點擊調用Java代碼</button><div id="content"></div></body></HTML>

 樣本比較簡單,注釋也寫的比較清楚不做過多的講解,全憑自己領悟。

本文出自 “墨宇遲傷” 部落格,請務必保留此出處http://zzhhz.blog.51cto.com/7107920/1861256

Android開發之WebView與js的資料傳遞

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.