Android的javascript扩展

/

软硬件环境

  • Macbook pro MGX 72
  • 红米Note增强版
  • Android studio 1.0.2

概述

Android的javascript扩展,即Android提供了javascript网页脚本调用java类方法的机制。方法其实很简单,只要调用addJavascriptInterface方法即可映射一个java对象到javascript对象。

示例

  • Android代码

    1. package com.macernow.djstava;
    2. import android.support.v7.app.ActionBarActivity;
    3. import android.os.Bundle;
    4. import android.util.Log;
    5. import android.view.Menu;
    6. import android.view.MenuItem;
    7. import android.webkit.JavascriptInterface;
    8. import android.webkit.WebView;
  1. public class MainActivity extends ActionBarActivity {
  2. private static final String TAG = "MainActivity";
  3. private WebView webView;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_main);
  8. webView = (WebView)findViewById(R.id.webView);
  9. webView.getSettings().setJavaScriptEnabled(true);
  10. webView.addJavascriptInterface(this,"djstava");
  11. webView.loadUrl("http://192.168.31.109/demo.html");
  12. }
  13. @JavascriptInterface
  14. public void jsextent() {
  15. Log.e(TAG,"========== js extension success.");
  16. }
  17. @Override
  18. public boolean onCreateOptionsMenu(Menu menu) {
  19. // Inflate the menu; this adds items to the action bar if it is present.
  20. getMenuInflater().inflate(R.menu.menu_main, menu);
  21. return true;
  22. }
  23. @Override
  24. public boolean onOptionsItemSelected(MenuItem item) {
  25. // Handle action bar item clicks here. The action bar will
  26. // automatically handle clicks on the Home/Up button, so long
  27. // as you specify a parent activity in AndroidManifest.xml.
  28. int id = item.getItemId();
  29. //noinspection SimplifiableIfStatement
  30. if (id == R.id.action_settings) {
  31. return true;
  32. }
  33. return super.onOptionsItemSelected(item);
  34. }
  35. }

WebView一定要使能javascript。在Android 4.2之后,抛出给javascript的java方法必须加上@JavascriptInterface

  • 布局文件

    1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    2. xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    3. android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    4. android:paddingRight="@dimen/activity_horizontal_margin"
    5. android:paddingTop="@dimen/activity_vertical_margin"
    6. android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    7. <WebView
    8. android:id="@+id/webView"
    9. android:layout_width="fill_parent"
    10. android:layout_height="fill_parent">
    11. </WebView>
    12. </RelativeLayout>
  • 测试页面

在javascript脚本中调用java方法

  1. window.djstava.jsextent()

工程下载

http://download.csdn.net/detail/djstava/8318657

转载请注明作者和出处,并添加本页链接。
原文链接:http://xugaoxiang.com/post/80

给我留言