1.如何建立android与javascript的交互

To bind a new interface between your JavaScript and Android code, call addJavascriptInterface(), passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.
For example:

public class WebActivity extends Activity {    private WebView webView;    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        getActionBar().hide();        //加载页面        webView = (WebView) findViewById(R.id.myweb);        //允许JavaScript执行        webView.getSettings().setJavaScriptEnabled(true);        //找到Html文件,也可以用网络上的文件        webView.loadUrl("file:///android_asset/index.html");        // 添加一个对象, 让JS可以访问该对象的方法, 该对象中可以调用JS中的方法        webView.addJavascriptInterface(new Contact(), "contact");        //让网页可以弹出alert、confrim对话框        webView.setWebChromeClient(new WebChromeClient() {});    }    private final class Contact {        //JavaScript调用此方法拨打电话        @JavascriptInterface        public void call(String phone) {            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone)));        }        @JavascriptInterface        public String getVersion()        {            String versionName = "";            try {                PackageInfo pi =  getPackageManager().getPackageInfo(getPackageName(), 0);                versionName = pi.versionName;                return versionName;            } catch (PackageManager.NameNotFoundException e) {                e.printStackTrace();            }            return versionName;        }        //Html调用此方法传递数据        @JavascriptInterface        public void showcontacts() {            System.out.println("---------showcontact---------");            final String json = "[{\"name\":\"zxx\", \"amount\":\"9999999\", \"phone\":\"18600012345\"}]";            // 调用JS中的方法            webView.post(new Runnable() {                @Override                public void run() {// webView.loadUrl("javascript: alert(" + data +")");                    webView.loadUrl("javascript:show('" + json + "')");                }            });        }    }}

html页面代码

<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title>Insert title here</title>    <script type="text/javascript"> function show(jsondata){ var jsonobjs = eval(jsondata); alert(jsonobjs[0].name); jsonobjs = [{"name":"zxx", "amount":"9999999", "phone":"18600012345"}]; var table = document.getElementById("personTable"); for(var y=0; y<jsonobjs.length; y++){ var tr = table.insertRow(table.rows.length); var td1 = tr.insertCell(0); var td2 = tr.insertCell(1); td2.align = "center"; td2.onclick = showVersion; var td3 = tr.insertCell(2); td3.align = "center"; td1.innerHTML = jsonobjs[y].name; td2.innerHTML = jsonobjs[y].amount; td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].phone+ "\")'>"+ jsonobjs[y].phone+ "</a>"; } } function showVersion() { alert(contact.getVersion()); } </script></head><body onload="javascript:contact.showcontacts()"><table border="0" width="100%" id="personTable" cellspacing="0">    <tr>        <td width="30%">姓名</td>        <td width="30%" align="center">存款</td>        <td align="center">电话</td>    </tr></table></body></html>

2.出现的一些问题

(1).W/WebView(2088): 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) {b3dbcb18} called on Looper (JavaBridge, tid 120) {b44a1af8}, FYI main Looper is Looper (main, tid 1) {b3dbcb18})

public void showcontacts() {            System.out.println("---------showcontact---------");            final String json = "[{\"name\":\"zxx\", \"amount\":\"9999999\", \"phone\":\"18600012345\"}]";            // 调用JS中的方法            webView.loadUrl("javascript:show('" + json + "')");        }

该方法如果这样直接调用javascript方法就会报上面错误。
(2).Uncaught TypeError: Object [object Object] has no method
下面是一些官方说明
Caution: If you’ve set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available to your JavaScript (the method must also be public). If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher.
(3).Uncaught ReferenceError: functionName is not defined
问题出现原因,网页的js代码没有加载完成,就调用了js方法。解决方法是在网页加载完成之后调用js方法。

myWebView.setWebViewClient(new WebViewClient() {  @Override  public void onPageFinished(WebView view, String url) {      super.onPageFinished(view, url);      //在这里执行你想调用的js函数  }});

更多相关文章

  1. android完全退出应用程序
  2. Android加载对话框,异步执行代码的封装类
  3. android 加载图片到gallery
  4. Gradle sync failed: Could not GET 'https://dl.google.com/dl/
  5. Android实际分辨率(android:anyDensity="false"的情况下的获取方
  6. android 中发送短信
  7. Android(安卓)存储选项之 SQLiteDatabase 创建过程源码分析
  8. Android面试系列文章2018之Android部分Fragment篇
  9. Android图表控件MPAndroidChart——LineChart实现 XY轴、原点线

随机推荐

  1. 用Eneter实现Android与.NET间通讯
  2. 活动与任务
  3. 打造android ORM框架opendroid(四)——优
  4. PHP android ios相互兼容的AES加密算法
  5. Android界面加载完成后自动弹出软键盘的
  6. 快速体验Android(安卓)2.3
  7. android map的使用方法
  8. Android打包jar 和使用第三方库
  9. [转]Android的Camera架构介绍[有图]
  10. Android核心功能