JavaScript与Java通信

来源:互联网 发布:mysql默认引擎 编辑:程序博客网 时间:2024/05/20 19:17

1、WebView中JavaScript调用Android程序中Java:

使用WebView类中的addJavascriptInterface()方法,可以使用它扩展嵌入式浏览器内的DOM(文档对象模型),并定义JavaScript代码可以访问的新对象。JavaScript代码调用该对象的方法时,实际上它会调用Android程序中的方法。


2、在Android程序中调用JavaScript方法:

调用loadUrl()方法,将URL以javascript:要执行的代码 的形式传递给它。浏览器会在当前页面执行给定的JavaScript表达式,而不是转到新的页面。


实例:


构建一个Android程序,布局如下(res/layout/activity_local_browser.xml)

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <WebView        android:id="@+id/web_view"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_weight="1.0" />    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_weight="1.0"        android:orientation="vertical" >        <TextView            android:id="@+id/url_field"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:text="@string/textview"/>        <Button            android:id="@+id/button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/call_javascript_from_android" />        <TextView             android:id="@+id/text_view"            android:layout_width="fill_parent"            android:layout_height="wrap_content"/>      </LinearLayout></LinearLayout>
可以看出,布局的上半部分是WeView控件,下部分是来自Android用户界面的TextView和Button。

下面需要完成将被加载到WebView中的index.html文件(assets/index.html),代码如下

<html><head><script language="JavaScript">function callJS(arg){document.getElementById('replaceme').innerHTML = arg;}</script></head><body><h1>WebView</h1><p><a href="#" onclick="window.alert('Alert from JavaScript')">Display JavaScript alert</a></p><p><a href="#" onclick="window.android.callAndroid('Hello from Browser')">Call Android from JavaScript</a></p><p id="replaceme"></p></body></html>

可以看到,callJS()函数是将会在Java代码中被调用JavaScript函数,它接收一个参数并赋值给replaceme标签。往下的两条链接分别是调用window.alert()函数(显示短消息)和window.android对象的callAndroid()方法(在Java代码中定义好的)。

同时不要忘记在res/values/strings.xml文件中完成字符串的赋值:

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="app_name">LocalBrower</string>    <string name="action_settings">Settings</string>    <string name="textview">TextView</string>    <string name="call_javascript_from_android">Call JavaScript from Android</string></resources>


完成这些准备后,就可以把目光放在程序的LocalBrowser类上了,代码如下:

package com.example.localbrowser;import android.support.v7.app.ActionBarActivity;import android.annotation.SuppressLint;import android.os.Bundle;import android.os.Handler;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.webkit.JavascriptInterface;import android.webkit.JsResult;import android.webkit.WebView;import android.webkit.WebChromeClient;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;@SuppressLint("JavascriptInterface")public class LocalBrowser extends ActionBarActivity {private WebView webview;private Button button;private TextView textview;private final Handler handler = new Handler();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_local_browser);webview = (WebView) findViewById(R.id.web_view);button = (Button) findViewById(R.id.button);textview = (TextView) findViewById(R.id.text_view);button.setOnClickListener(new OnClickListener() {public void onClick(View view) {//单击按钮时,通过WebView.loadUrl()方法调用index.html中定义的callJS()函数webview.loadUrl("javascript:callJS('Hello from Android')");}});//打开JavaScript(默认是关闭的)webview.getSettings().setJavaScriptEnabled(true);//往WebView中注入Java对象,从而使得在index.tml中能使用此对象的方法webview.addJavascriptInterface(new AndroidBridge(), "android");webview.setWebChromeClient(new WebChromeClient() {// 覆盖默认的window.alert()的展示界面public boolean onJsAlert(final WebView view, final String url,final String message, JsResult result) {Toast.makeText(LocalBrowser.this, message, 3000).show();result.confirm();return true;}});webview.loadUrl("file:///android_asset/index.html");//加载本地网页,注意有3个斜杠}public class AndroidBridge {@JavascriptInterface// 要通过JavaScript调用的Java代码片段public void callAndroid(final String arg) {handler.post(new Runnable() {public void run() {textview.setText(arg);}});}}}

整个过程很简单,但有点要注意的是:

在AdroidBridge类中

4.2之前向WebView注入的对象所暴露的接口callAndroid没有注释语句@JavascriptInterface,而4.2及以后的则多了注释语句@JavascriptInterface。如果去掉这行代码,当程序调用此方法时,将不能成功,而logcat会报如下输出:

E/Web Console: Uncaught TypeError: Object [object Object] has no method 'callAndroid'


程序界面:



当单击按钮和链接时,它会在两个环境间进行调用,下面是运行效果图









4 2
原创粉丝点击