标签:
实现Java和js交互十分便捷。通常只需要以下几步。
#直接看示例代码:
java代码如下:
package com.ccb.javascript; import java.net.URISyntaxException; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; @TargetApi(Build.VERSION_CODES.DONUT) public class JavaScriptDemo extends Activity { private static final String LOGTAG = "MainActivity"; @SuppressLint("JavascriptInterface") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.javascriptdemo); final WebView myWebView = (WebView) findViewById(R.id.myWebView); WebSettings settings = myWebView.getSettings(); settings.setJavaScriptEnabled(true); myWebView.addJavascriptInterface(new JsInteration(), "control"); myWebView.setWebChromeClient(new WebChromeClient() { }); myWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); testMethod(myWebView); } }); myWebView.loadUrl("file:///android_asset/js_java_interaction.html"); } private void testMethod(WebView webView) { String call = "javascript:sayHello()"; call = "javascript:alertMessage(\"" + "content" + "\")"; call = "javascript:toastMessage(\"" + "content" + "\")"; call = "javascript:sumToJava(1,2)"; webView.loadUrl(call); } public class JsInteration { @JavascriptInterface public Intent toastMessage(String message) { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG) .show(); Intent intent = null; // Parse intent URI into Intent Object int flags = 0; boolean isIntentUri = false; if (message.startsWith("intent:")) { isIntentUri = true; flags = Intent.URI_INTENT_SCHEME; } else if (message.startsWith("#Intent;")) { isIntentUri = true; } if (isIntentUri) { try { intent = Intent.parseUri(message, flags); } catch (URISyntaxException e) { e.printStackTrace(); } } startActivity(intent); return intent; } @JavascriptInterface public void onSumResult(int result) { Log.i(LOGTAG, "onSumResult result=" + result); } } }
<html> <script type="text/javascript"> function sayHello() { alert("Hello") } function alertMessage(message) { alert(message) } function toastMessage(message) { window.control.toastMessage(message) } function sumToJava(number1, number2){ window.control.onSumResult(number1 + number2) } </script> Java-Javascript Interaction In Android <br /> <a onClick="window.control.toastMessage(‘#Intent;component=com.ccb.javascript/com.ccb.javascript.MainActivity;end‘)" href="";>调用java中的方法</a> </html>
调用格式为window.jsInterfaceName.methodName(parameterValues) 此例中我们使用的是control作为注入接口名称。
具体调用:
<a onClick="window.control.toastMessage(‘#Intent;component=com.ccb.javascript/com.ccb.javascript.MainActivity;end‘)" href="";>调用java中的方法</a>
(‘#Intent;component=com.ccb.javascript/com.ccb.javascript.MainActivity;end‘) 是传递一个打开Activity的Intent。也可以是字符串或者其他。
webView调用js的基本格式为webView.loadUrl(“javascript:methodName(parameterValues)”)
String call = "javascript:sayHello()"; webView.loadUrl(call);
注意对于字符串作为参数值需要进行转义双引号。
String call = "javascript:alertMessage(\"" + "content" + "\")"; webView.loadUrl(call);
Android在4.4之前并没有提供直接调用js函数并获取值的方法,所以在此之前,常用的思路是 java调用js方法,js方法执行完毕,再次调用java代码将值返回。
String call = "javascript:sumToJava(1,2)"; webView.loadUrl(call);
function sumToJava(number1, number2){ window.control.onSumResult(number1 + number2) }
@JavascriptInterface public void onSumResult(int result) { Log.i(LOGTAG, "onSumResult result=" + result); }
Android 4.4之后使用evaluateJavascript即可。这里展示一个简单的交互示例 具有返回值的js方法
function getGreetings() { return 1; } java代码时用evaluateJavascript方法调用 private void testEvaluateJavascript(WebView webView) { webView.evaluateJavascript("getGreetings()", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { Log.i(LOGTAG, "onReceiveValue value=" + value); }}); } 输出结果: I/MainActivity( 1432): onReceiveValue value=1 注意 上面限定了结果返回结果为String,对于简单的类型会尝试转换成字符串返回,对于复杂的数据类型,建议以字符串形式的json返回。 evaluateJavascript方法必须在UI线程(主线程)调用,因此onReceiveValue也执行在主线程。
你应该是没有设置WebChromeClient,按照以下代码设置
myWebView.setWebChromeClient(new WebChromeClient() {});
问题出现原因,网页的js代码没有加载完成,就调用了js方法。解决方法是在网页加载完成之后调用js方法
myWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); //在这里执行你想调用的js函数 } });
如果只在4.2版本以上的机器出问题,那么就是系统处于安全限制的问题了。Android文档这样说的
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.
中文大意为
警告:如果你的程序目标平台是17或者是更高,你必须要在暴露给网页可调用的方法(这个方法必须是公开的)加上@JavascriptInterface注释。如果你不这样做的话,在4.2以以后的平台上,网页无法访问到你的方法。
注,创建@JavascriptInterface代码
public @interface JavascriptInterface { }
如果在没有混淆的版本运行正常,在混淆后的版本的代码运行错误,并提示Uncaught TypeError: Object [object Object] has no method,那就是你没有做混淆例外处理。 在混淆文件加入类似这样的代码
keepattributes *Annotation* keepattributes JavascriptInterface -keep class com.example.javajsinteractiondemo$JsInteration { *; }
All WebView methods must be called on the same thread 过滤日志曾发现过这个问题。
E/StrictMode( 1546): java.lang.Throwable: A WebView method was called on thread ‘JavaBridge‘. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {528712d4} called on Looper (JavaBridge, tid 121) {52b6678c}, FYI main Looper is Looper (main, tid 1) {528712d4}) E/StrictMode( 1546): at android.webkit.WebView.checkThread(WebView.java:2063) E/StrictMode( 1546): at android.webkit.WebView.loadUrl(WebView.java:794) E/StrictMode( 1546): at com.xxx.xxxx.xxxx.xxxx.xxxxxxx$JavaScriptInterface.onCanGoBackResult(xxxx.java:96) E/StrictMode( 1546): at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method) E/StrictMode( 1546): at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27) E/StrictMode( 1546): at android.os.Handler.dispatchMessage(Handler.java:102) E/StrictMode( 1546): at android.os.Looper.loop(Looper.java:136) E/StrictMode( 1546): at android.os.HandlerThread.run(HandlerThread.java:61)
在js调用后的Java回调线程并不是主线程。如打印日志可验证
ThreadInfo=Thread[WebViewCoreThread,5,main]
解决上述的异常,将webview操作放在主线程中即可。
webView.post(new Runnable() { @Override public void run() { webView.loadUrl(YOUR_URL). } });
转自:http://droidyue.com/blog/2014/09/20/interaction-between-java-and-javascript-in-android/
标签:
原文地址:http://www.cnblogs.com/spring87/p/4530800.html