标题: android与javascript交互 [打印本页]

作者: 51hei小林    时间: 2016-9-25 11:04
标题: android与javascript交互
Android与Javascript交互主要是使用的WebView。

关于WebView,一般涉及到2个类:WebChromeClient 和 WebViewClient 。
开发的大致流程为(摘自Android developer):
A WebView has several customization points where you can add your own behavior. These are:
Creating and setting a WebChromeClient subclass. This class is called when something that might impact a browser UI happens, for instance, progress updates and JavaScript alerts are sent here (see Debugging Tasks).
Creating and setting a WebViewClient subclass. It will be called when things happen that impact the rendering of the content, eg, errors or form submissions. You can also intercept URL loading here (via shouldOverrideUrlLoading()).
Modifying the WebSettings, such as enabling JavaScript with setJavaScriptEnabled().
Injecting Java objects into the WebView using the addJavascriptInterface(Object, String) method. This method allows you to inject Java objects into a page's JavaScript context, so that they can be accessed by JavaScript in the page.
好了,废话不多说,上Demo。
此demo完成了Android与Javascript交互的基础功能,并用json字符串进行了值传递。
秉持一贯的风格,知识内容都在代码注释中,这样方便以后复习。(布局就不贴了,比较简单)
整个工程结构比较简单:



首先是这个jsdroid.html文件的界面(贴界面其实有点2 --!):


html代码比较简单:

[html] view plain copy
print?




其中,id为“btn_pmt”的button,监听器设置的是调用Android中的方法。

好了,上最重要的,android端实现的代码。

[java] view plain copy
print?





这只是粗略地学习了下android和Javascript的交互,后面的,还需要继续深入研究下。

最终在手机上跑的效果图:



Demo的下载地址:
http://download.csdn.net/detail/singleton1900/5238800









欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1