android中通过WebView控件可以加载网页和本地的html文件。下面是一个简单的android与js交互Demo。

主类:

public class MainActivity extends Activity {WebView webview;Button btn;@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);webview = (WebView) findViewById(R.id.webView);webview.getSettings().setJavaScriptEnabled(true);// 设置js属性可用为truewebview.loadUrl("file:///android_asset/index.html");// 加载本地的html文件webview.addJavascriptInterface(this, "demo");// 与js交互的接口,第一个参数可以是本类this,也可new一个类,第二个参数为接口别名。btn = (Button) findViewById(R.id.btn);btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubwebview.loadUrl("javascript:javacalljs()");// java代码调用js中的方法}});}@JavascriptInterface// 注意:此处在android api17及以上必须声明@JavascriptInterface,并且必须在js所调用的方法前,否则js会调不到// 此方法,也就是说js调java无反应。关于此处还与硬件的rom版本有关。需具体问题具体分析。public void startNewActivity() {Toast.makeText(this, "js调用了java函数", Toast.LENGTH_SHORT).show();runOnUiThread(new Runnable() {@Overridepublic void run() {// 在此处进行要实现的操作,本demmo演示调用其他程序功能Intent intent = new Intent(Intent.ACTION_MAIN);intent.addCategory(Intent.CATEGORY_LAUNCHER);ComponentName cn = new ComponentName("包名", "类名");intent.setComponent(cn);startActivity(intent);}});}}

布局文件xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@android:color/transparent" >    <WebView        android:id="@+id/webView"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <Button        android:id="@+id/btn"        android:layout_width="30dp"        android:layout_height="30dp"        android:layout_below="@+id/webView"        android:text="android按钮" /></RelativeLayout>

本地的html文件:

此文件要放在assets文件夹下。

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script type="text/javascript" language="javascript">function javacalljs(){ document.getElementById("content").innerHTML +=            "<br\>java调用了js函数";}</script></head><body><Button onclick="window.demo.startNewActivity()">点我进行js调用java方法</Button><div id="content">内容显示</div></body></html>

更多相关文章

  1. C语言函数以及函数的使用
  2. Android 入门第八讲02-WebView的高级用法(Android调用 JS 代码( lo
  3. Android加密之文件级加密
  4. Android(二)数据存储和访问 之文件
  5. Android 读写Excel文件
  6. 获取Android的Java源代码并在Eclipse中关联查看的最新方法

随机推荐

  1. Android(安卓)横屏时禁止输入法全屏
  2. android调用系统打电话功能
  3. Android实现画虚线的控件
  4. android CTS SELinuxDomainTest# testIni
  5. android wegit 组件
  6. androidのview游戏框架
  7. 判断android devices是否联网
  8. Android学习之ListView使用基础
  9. 【Android】进程与线程基本知识
  10. android经典优化点