Android调用js的问题

JavaScript08

Android调用js的问题,第1张

Android中可以使用WebView加载网页,同时Android端的java代码可以与网页上的javascript代码之间相互调用。

一 Android部分:

布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableInTouchMode="true" android:orientation="vertical" android:padding="8dp" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/input_et" android:layout_width="0dp" android:layout_height="wrap_content" android:singleLine="true" android:layout_weight="1" android:hint="请输入信息" /> <Button android:text="Java调用JS" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="sendInfoToJs" /></LinearLayout> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>

Activity代码:

public class MainActivity extends AppCompatActivity { private WebView webView @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) webView = (WebView) findViewById(R.id.webView) webView.setVerticalScrollbarOverlay(true) //设置WebView支持JavaScript webView.getSettings().setJavaScriptEnabled(true) webView.loadUrl("file:///android_asset/webview.html") //在js中调用本地java方法 webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView") ////添加客户端支持 webView.setWebChromeClient(new WebChromeClient()) } private class JsInterface { private Context mContext public JsInterface(Context context) { this.mContext = context } //在js中调用window.AndroidWebView.showInfoFromJs(name),便会触发此方法。 @JavascriptInterface public void showInfoFromJs(String name) { Toast.makeText(mContext, name, Toast.LENGTH_SHORT).show() } } //在java中调用js代码 public void sendInfoToJs(View view) { String msg = ((EditText) findViewById(R.id.input_et)).getText().toString() //调用js中的函数:showInfoFromJava(msg) webView.loadUrl("javascript:showInfoFromJava('" + msg + "')")//webView.loadUrl("javascript:showInfoFromJava()") } }

二 网页代码

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Android WebView 与 Javascript 交互</title> </head><body><input type="button" value="分享" onclick="f1()"> <input type="text" id="show"/> </body><script> function f1(){ AndroidWebView.showInfoFromJs("hello")} function showInfoFromJava(msg){ document.getElementById("show").value=msgalert(1) }</script></html>

注意: android 调用js代码可能会报错如下:

W/WebView(2088): java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread.

解决办法:

webView.post(new Runnable() { @Override public void run() { webView.loadUrl("javascript:showInfoFromJava('" + msg + "')")}})

Android中内置了WebKit模块,而该模块的Java层视图类就是WebView,所有需要使用Web浏览器功能的Android都需要创建该视图类对象显示和处理请求的网络资源。目前WebKit支持Http、Https、Ftp和JavaScript请求。

1、在Assets下放一个简单的html文件jstest.html

<HTML>

<HEAD>

<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi" />

<META http-equiv="Content-Type" content="text/html charset=UTF-8">

<script>

   function showMsg(){

      alert("hello world!")

   }

   function showMsgInAndroid(){

      myjs.showMsg('hello in android!')

   }

</script>

</HEAD>

<BODY>

<span>测试js使用</span>

<button id='btntest' onclick='showMsgInAndroid()'>调用android方法</button>

</BODY>

</HTML>

2、布局文件main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

android:id="@+id/rl_main"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

xmlns:android="http://schemas.android.com/apk/res/android"

    >

   <WebView 

       android:id="@+id/wv_test"

       android:layout_width="fill_parent"

       android:layout_height="fill_parent"

       android:layout_above="@+id/btn_showmsg"/>

   <Button 

       android:id="@+id/btn_showmsg"

       android:layout_width="200dip"

       android:layout_height="40dip"

       android:layout_alignParentBottom="true"

       android:layout_centerHorizontal="true"

       android:text="调用html中js方法"/>

</RelativeLayout>

3、然后是Activity,MainActivity.java

package com.harold.jstest

import com.harold.base.JSKit

import android.app.Activity

import android.os.Bundle

import android.os.Handler

import android.view.View

import android.view.View.OnClickListener

import android.webkit.WebChromeClient

import android.webkit.WebView

import android.widget.Button

public class MainActivity extends Activity {

private WebView mWebView

private Button btnShowInfo

private JSKit js

private Handler mHandler = new Handler()

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState)

setContentView(R.layout.main)

//初始化控件

mWebView = (WebView) findViewById(R.id.wv_test)

btnShowInfo = (Button) findViewById(R.id.btn_showmsg)

//实例化js对象

js = new JSKit(this)

//设置参数

mWebView.getSettings().setBuiltInZoomControls(true)

//内容的渲染需要webviewChromClient去实现,

//设置webviewChromClient基类,解决js中alert不弹出的问题和其他内容渲染问题

mWebView.setWebChromeClient(new WebChromeClient())

mWebView.getSettings().setJavaScriptEnabled(true)

//把js绑定到全局的myjs上,myjs的作用域是全局的,初始化后可随处使用

mWebView.addJavascriptInterface(js, "myjs")

mWebView.loadUrl("file:///android_asset/jstest.html")

btnShowInfo.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

mHandler.post(new Runnable() {

@Override

public void run() {

//调用 HTML 中的javaScript 函数

mWebView.loadUrl("javascript:showMsg()")

}

})

}

})

}

}