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. android EditText 如何限制只能输入指定的字符
  2. Android中接口的使用及类使用
  3. Android应用开发相关下载资源
  4. Android布局图标中心化
  5. 【Android】Android的Activity生命周期
  6. Android中使用sqlite笔记
  7. Android(安卓)结束进程的方法
  8. Android(安卓)getResources的作用和需要注意点
  9. Android(安卓)SDK下载和更新失败的解决方法

随机推荐

  1. 总结一些更多的针对webkit的HTML, CSS和J
  2. 韩顺平_轻松搞定网页设计(html+css+javas
  3. Python-html课程基础复习
  4. html中页面传递参数不用cookie不用缓存,j
  5. sp_send_dbmail在body中嵌入mhtml文件
  6. 2个div内容交换不用innerHTML似乎办不到?
  7. 8.HTML5 CSS3 背景、边框与补丁相关属性
  8. 我想把桌子设置成全高和宽
  9. HTML中上传与读取图片或文件(input file)--
  10. 扩展htmlhelper.DropDownListFor 支持lis