Android 中 js 和 原生交互

 

Android中的WebView 中加載的URL 默認是在手機瀏覽器中加載的,我們可以覆蓋這種默認的動作,讓網頁在WebView中打開。通過設置WebView的WebViewClent 達到這個效果。

WebView中加載的網頁中的JS事件可用和Native 代碼交互。js 如何調用原生中的方法呢?

 

1.設置WebView中的JavaScript可用

 

2.設置WebView的JavascriptInterface  即原生中與js的接口

 

源碼: 在 Activity中聲明瞭一個 JavaScriptInterface 類,在這個類中定義了js中可以調用的方法。

 

js中調用的方法 需要加註解  @JavascriptInterface

package com.example.hybridtest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		JavaScriptInterface JSInterface;
		WebView wv;
		wv = (WebView) findViewById(R.id.webView1);
		wv.getSettings().setJavaScriptEnabled(true); ///------- 設置javascript 可用
		JSInterface = new JavaScriptInterface(this); ////------ 
		wv.addJavascriptInterface(JSInterface, "JSInterface"); // 設置js接口  第一個參數事件接口實例,第二個是實例在js中的別名,這個在js中會用到
		wv.loadUrl("file:///android_asset/test.html");
	}
public class JavaScriptInterface { Context mContext; JavaScriptInterface(Context c) { mContext = c; } @JavascriptInterface public void changeActivity() { Intent i = new Intent(MainActivity.this, NextActivity.class); startActivity(i); finish(); } } }

  

html中 button的響應事件中 直接調用了原生中的方法:JSInterface.changeActivity(); 實現了頁面跳轉。

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
JSInterface.changeActivity();
}
</script>
</head>

<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>

 Android 4.2 文檔:

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

 如果你想讓方法可以在javascript中調用的話 需要在方法上添加 註解.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章