閱讀388 返回首頁    go 阿裏雲 go 技術社區[雲棲]


android客戶端和服務端js交互


挺帥的移動開發專欄  https://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支持

  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()");  
		// 啟用javascript
		contentWebView.getSettings().setJavaScriptEnabled(true);
		// 從assets目錄下麵的加載html
		contentWebView.loadUrl("file:///android_asset/wst.html");

                // 無參數調用
	        contentWebView.loadUrl("javascript:javacalljs()");

功能二
webview中js調用本地java方法,這個功能實現起來稍微有點麻煩,不過也不怎麼複雜,首先要對webview綁定javascriptInterface,js腳本通過這個接口來調用java代碼。
  1. contentWebView.addJavascriptInterface(this"wst");  
		contentWebView.addJavascriptInterface(this, "wst");
javainterface實際就是一個普通的java類,裏麵是我們本地實現的java代碼, 將object 傳遞給webview,並指定別名,這樣js腳本就可以通過我們給的這個別名來調用我們的方法,在上麵的代碼中,this是實例化的對象,wst是這個對象在js中的別名

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

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

這裏準備了一個實例,實現上麵的功能

這裏是實例的html代碼,從assert中加載,原來做項目的時候,從assert中加載的中文網頁會出現亂碼,解決辦法就是給html指定編碼。如下


  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>  
<html>
<head>
<meta http-equiv="Content-Type"	content="text/html;charset=gb2312">
<script type="text/javascript">
function javacalljs(){
	 document.getElementById("content").innerHTML +=   
         "<br\>java調用了js函數";
}

function javacalljswithargs(arg){
	 document.getElementById("content").innerHTML +=   
         ("<br\>"+arg);
}

</script>
</head>
<body>
this is my html <br/>
<a onClick="window.wst.startFunction()">點擊調用java代碼</a><br/>
<a onClick="window.wst.startFunction('hello world')" >點擊調用java代碼並傳遞參數</a>
<br/>
<div >內容顯示</div>
</body>
</html>

java代碼 如下

  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. }  
package wst.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private WebView contentWebView = null;
	private TextView msgView = null;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		contentWebView = (WebView) findViewById(R.id.webview);
		msgView = (TextView) findViewById(R.id.msg);
		// 啟用javascript
		contentWebView.getSettings().setJavaScriptEnabled(true);
		// 從assets目錄下麵的加載html
		contentWebView.loadUrl("file:///android_asset/wst.html");

		Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(btnClickListener);
		contentWebView.addJavascriptInterface(this, "wst");
	}

	OnClickListener btnClickListener = new Button.OnClickListener() {
		public void onClick(View v) {
			// 無參數調用
			contentWebView.loadUrl("javascript:javacalljs()");
			// 傳遞參數調用
			contentWebView.loadUrl("javascript:javacalljswithargs(" + "'hello world'" + ")");
		}
	};

	public void startFunction() {
		Toast.makeText(this, "js調用了java函數", Toast.LENGTH_SHORT).show();
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				msgView.setText(msgView.getText() + "\njs調用了java函數");

			}
		});
	}

	public void startFunction(final String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				msgView.setText(msgView.getText() + "\njs調用了java函數傳遞參數:" + str);

			}
		});
	}
}

布局文件

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="https://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>  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
        android:
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="9" />

    <ScrollView
        android:
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="text" />
    </ScrollView>

    <Button
        android:
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="java調用js函數" />

</LinearLayout>

希望對大家有所幫助
資源下載地址

最後更新:2017-04-03 12:54:29

  上一篇:go 一個不錯的定時程序,寫的很好的
  下一篇:go JAVA獲取圖片大小和尺寸