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中调用的话 需要在方法上添加 注解.

原文地址:https://www.cnblogs.com/igoogleyou/p/androidwv11.html