webview的javascript與Native code互動

來源:互聯網
上載者:User

標籤:

http://my.oschina.net/u/1376187/blog/172296

  項目中使用了webview顯示網頁,其中需要網頁和native方法有互動,搜尋到一篇文章,轉寄分享一下:

==============================================================================================================================

 

 轉載請註明出處        挺帥的移動開發專欄  http://blog.csdn.net/wangtingshuai/article/details/8631835       在android的開發過程中,有很多時候需要用到本地java代碼和javascript進行互動。android對互動進行了很好的封裝,在開發中我們可以很簡單的用java代碼調用webview中的js,也可以用webview中的js來調用本地的java代碼, 這樣我們可以實現很多原來做不了的功能,比如點擊網頁上的電話號碼後,手機自動撥打到電話,點擊網頁中的笑話,自動傳送簡訊等. 廢話不多說,這次教程的目標如下
  1. android 中的java代碼調用webview裡面的js指令碼
  2. webview中的js指令碼調用本地的java代碼
  3. java調用js並傳遞參數
  4. js調用java並傳遞參數
功能一 android中調用webview中的js指令碼非常方便,只需要調用webview的loadUrl方法即可( 注意開啟js支援) 

 

[html]  view plain copy 
  1. // 啟用javascript  
  2. contentWebView.getSettings().setJavaScriptEnabled(true);  
  3. // 從assets目錄下面的載入html  
  4. contentWebView.loadUrl("file:///android_asset/wst.html");  
  5.   
  6.               // 無參數調用  
  7.        contentWebView.loadUrl("javascript:javacalljs()");  
 功能二 
webview中js調用本地java方法,這個功能實現起來稍微有點麻煩,不過也不怎麼複雜,首先要對webview綁定javascriptInterface,js指令碼通過這個介面來調用java代碼。[java]  view plain copy 
  1. contentWebView.addJavascriptInterface(this, "wst");  
javainterface實際就是一個普通的java類,裡面是我們本地實現的java代碼, 將object 傳遞給webview,並指定別名,這樣js指令碼就可以通過我們給的這個別名來調用我們的方法,在上面的代碼中,this是執行個體化的對象,wst是這個對象在js中的別名  

功能三 
java代碼調用js並傳遞參數 
只需要在待用js函數的時候加入參數即可,下面是傳遞一個參數的情況,需要多個參數的時候自己拼接及行了,注意str類型在傳遞的時候參數要用單引號括起來

[java]  view plain copy 
  1. mWebView.loadUrl("javascript:test(‘" + aa+ "‘)"); //aa是js的函數test()的參數  
功能四 
js調用java函數並傳參,java函數正常書寫,在js指令碼中調用的時候稍加註意 
然後在html頁面中,利用如下代碼,即可實現調用[html]  view plain copy 
  1. <div id=‘b‘><a onclick="window.wst.clickOnAndroid(2)">b.c</a></div>  

這裡準備了一個執行個體,實現上面的功能 這裡是執行個體的html代碼,從assert中載入,原來做項目的時候,從assert中載入的中文網頁會出現亂碼,解決辦法就是給html指定編碼。如下 
[html]  view plain copy 
  1. <html>  
  2. <head>  
  3. <meta http-equiv="Content-Type"  content="text/html;charset=gb2312">  
  4. <script type="text/javascript">  
  5. function javacalljs(){  
  6.      document.getElementById("content").innerHTML +=     
  7.          "<br\>java調用了js函數";  
  8. }  
  9.   
  10. function javacalljswithargs(arg){  
  11.      document.getElementById("content").innerHTML +=     
  12.          ("<br\>"+arg);  
  13. }  
  14.   
  15. </script>  
  16. </head>  
  17. <body>  
  18. this is my html <br/>  
  19. <a onClick="window.wst.startFunction()">點擊調用java代碼</a><br/>  
  20. <a onClick="window.wst.startFunction(‘hello world‘)" >點擊調用java代碼並傳遞參數</a>  
  21. <br/>  
  22. <div id="content">內容顯示</div>  
  23. </body>  
  24. </html>  

java代碼 如下 

[java]  view plain copy 
  1. package wst.webview;  
  2.   
  3. import android.annotation.SuppressLint;  
  4. import android.app.Activity;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.webkit.WebView;  
  9. import android.widget.Button;  
  10. import android.widget.TextView;  
  11. import android.widget.Toast;  
  12.   
  13. public class MainActivity extends Activity {  
  14.   
  15.     private WebView contentWebView = null;  
  16.     private TextView msgView = null;  
  17.   
  18.     @SuppressLint("SetJavaScriptEnabled")  
  19.     @Override  
  20.     public void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.main);  
  23.         contentWebView = (WebView) findViewById(R.id.webview);  
  24.         msgView = (TextView) findViewById(R.id.msg);  
  25.         // 啟用javascript  
  26.         contentWebView.getSettings().setJavaScriptEnabled(true);  
  27.         // 從assets目錄下面的載入html  
  28.         contentWebView.loadUrl("file:///android_asset/wst.html");  
  29.   
  30.         Button button = (Button) findViewById(R.id.button);  
  31.         button.setOnClickListener(btnClickListener);  
  32.         contentWebView.addJavascriptInterface(this, "wst");  
  33.     }  
  34.   
  35.     OnClickListener btnClickListener = new Button.OnClickListener() {  
  36.         public void onClick(View v) {  
  37.             // 無參數調用  
  38.             contentWebView.loadUrl("javascript:javacalljs()");  
  39.             // 傳遞參數調用  
  40.             contentWebView.loadUrl("javascript:javacalljswithargs(" + "‘hello world‘" + ")");  
  41.         }  
  42.     };  
  43.   
  44.     public void startFunction() {  
  45.         Toast.makeText(this, "js調用了java函數", Toast.LENGTH_SHORT).show();  
  46.         runOnUiThread(new Runnable() {  
  47.   
  48.             @Override  
  49.             public void run() {  
  50.                 msgView.setText(msgView.getText() + "\njs調用了java函數");  
  51.   
  52.             }  
  53.         });  
  54.     }  
  55.   
  56.     public void startFunction(final String str) {  
  57.         Toast.makeText(this, str, Toast.LENGTH_SHORT).show();  
  58.         runOnUiThread(new Runnable() {  
  59.   
  60.             @Override  
  61.             public void run() {  
  62.                 msgView.setText(msgView.getText() + "\njs調用了java函數傳遞參數:" + str);  
  63.   
  64.             }  
  65.         });  
  66.     }  
  67. }  

布局檔案 [html]  view plain copy 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <WebView  
  8.         android:id="@+id/webview"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="fill_parent"  
  11.         android:layout_weight="9" />  
  12.   
  13.     <ScrollView  
  14.         android:id="@+id/scrollView1"  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="wrap_content" >  
  17.   
  18.         <TextView  
  19.             android:id="@+id/msg"  
  20.             android:layout_width="fill_parent"  
  21.             android:layout_height="fill_parent"  
  22.             android:text="text" />  
  23.     </ScrollView>  
  24.   
  25.     <Button  
  26.         android:id="@+id/button"  
  27.         android:layout_width="fill_parent"  
  28.         android:layout_height="wrap_content"  
  29.         android:layout_weight="1"  
  30.         android:text="java調用js函數" />  
  31.   
  32. </LinearLayout>  

希望對大家有所協助資源

http://download.csdn.net/download/wangtingshuai/5106571

 

====================================================================================================================

結尾總結幾句:

1、webview load網頁時,native code能和網頁中的js相互互動並傳遞參數(一個參數)。

2、js調用native code那部分一下子可能看得不是很明白,這裡整理一下:

?
12345678910111213141516171819202122 //native code方面//使用addJavascriptInterface綁定“wst”contentWebView.addJavascriptInterface(this, "wst");… //添加需要響應的方法,注意必須為publicpublic void startFunction(final String str) {          Toast.makeText(this, "js調用了java函數", Toast.LENGTH_SHORT).show();          runOnUiThread(new Runnable() {                 @Override              public void run() {                  msgView.setText(msgView.getText() + "\njs調用了java函數");                 }          });      }   //js方面<a onClick="window.wst.startFunction(‘hello world‘)" >點擊調用java代碼並傳遞參數</a><span><span style="line-height:20px;"> </span></span>
分享到:  

webview的javascript與Native code互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.