背景介绍
Android下面WebView开发,有时候需要调用底层的一部分接口,而这部分接口只有Android的SDK才提供相关的功能,这个时候就需要进行Java与JavaScript通信。
例子
- 生成JavaScript调用Java函数的接口类
123456public class AndroidJavaScript {@JavascriptInterfacepublic String getJavaString() {return new String("JavaString");}} - 开启 JavaScript支持,并向WebView注册接口
12mWebView.getSettings().setJavaScriptEnabled(true);mWebView.addJavascriptInterface(new AndroidJavaScript(), "Android"); - Html中调用接口例子
12345678<html><head><script type="text/javascript">var JavaString = window.Android.getJavaString()document.write(JavaString);</script></head></html> - 销毁的时候,反注册接口,避免内存泄漏
1mWebView.removeJavascriptInterface("Android"); - 销毁的时候,WebView从父容器中移除,避免内存泄漏
123456ViewParent viewParent = mWebView.getParent();if(viewParent instanceof ViewGroup) {ViewGroup viewGroup = (ViewGroup)viewParent;viewGroup.removeView(mWebView);}mWebView.destroy();
完整的例子代码如下(包含WebView的XML布局文件,请自行生成):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup; import android.view.ViewParent; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; public class MainActivity extends Activity { WebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = (WebView)findViewById(R.id.jsBridgeWebView); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.addJavascriptInterface(new AndroidJavaScript(), mJsInterfaceName); mWebView.loadDataWithBaseURL("blarg://ignored", mJsHtml, "text/html", "UTF-8", ""); } @Override protected void onDestroy() { mWebView.removeJavascriptInterface(mJsInterfaceName); ViewParent viewParent = mWebView.getParent(); if(viewParent instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup)viewParent; viewGroup.removeView(mWebView); } mWebView.destroy(); super.onDestroy(); } private static class AndroidJavaScript { @JavascriptInterface public String getString() { return new String("JavaString"); } } private final String mJsInterfaceName = "Android"; private final String mJsHtml = "<html>\n" + "\t<head>\n" + "\t\t<script type=\"text/javascript\">\n" + "\t\t\tvar str = window.Android.getString()\r\n" + "\t\t\tdocument.write(str)\n" + "\t\t</script>\n" + "\t</head>\n" + "</html>"; } |