Android—android与js交互以及相互传参

时间:2021-09-10 16:51:13

Android中可以通过WebView来实现与js的交互,让用户可以在android客户端看到js写的页面,接下来为大家介绍的就是怎样实现此功能:

首先android项目目录下有“assets”文件夹,开发者需要将html文件拷贝到此文件夹下。

html代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0032)http://localhost:8080/jsandroid/ -->
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-store,no-cache">
<meta name="Handheldfriendly" content="true">
<meta name="viewport" content="width=100%; initial-scale=1.0; user-scalable=yes">
<meta name="robots" content="all">
<meta name="keywords" contect="doodle, mobile, doodlemobile, game, games">
<meta name="description" content="Make People's Mobile Life More Connected Through Games.">
<title>jsandroid_test</title>
<script type="text/javascript" language="javascript">
//此方法是调用了android的方法HtmlcallJava2();
function showHtmlcallJava2(){
var str = document.getElementById("id_input").value
var str1 = document.getElementById("id_input2").value
//调用android中的方法
window.jsObj.HtmlcallJava2(str+","+str1);
} </script> </head> <body> hello IT-homer <br>
<br>
<br>
<br> <input id="id_input" style="width: 90%" type="text" value="null" />
<br>
<br> <input id="id_input2" style="width: 90%" type="text" value="null" />
<br>
</body> </html>

xml布局文件,很简单:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".JSAndroidActivity" > <WebView
android:id="@+id/mWebView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clickView"
android:text="获取" /> </LinearLayout>
mainActivity中的核心代码是:
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(jsInterface, "jsObj");
mWebView.loadUrl("file:///android_asset/index.html");
请理解核心代码的详细注释 mainActivity代码:
package com.homer.jsandroid;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer; import android.R.anim;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast; public class JSAndroidActivity extends Activity {
private Activity mActivity = null;
private WebView mWebView = null;
private String message;
private JsInterface jsInterface;
private String[] params = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = this;
// 锁定横屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.main);
params = new String[2];
jsInterface = new JsInterface();
showWebView();
} @SuppressLint("SetJavaScriptEnabled")
private void showWebView() {
try {
mWebView = (WebView) findViewById(R.id.mWebView); mWebView.requestFocus(); mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int progress) {
JSAndroidActivity.this.setTitle("Loading...");
JSAndroidActivity.this.setProgress(progress);
if (progress >= 80) {
JSAndroidActivity.this.setTitle("JsAndroid Test");
}
}
}); mWebView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return false;
}
});
// WebView的管理设置状态
WebSettings webSettings = mWebView.getSettings();
// 设置android下容许执行js的脚本
webSettings.setJavaScriptEnabled(true);
// 编码方式
webSettings.setDefaultTextEncodingName("utf-8");
/*
* 使用这个函数将一个对象绑定到Javascript,因此可以从Javascript访问的方法,
* Android(Java)与js(HTML)交互的接口函数, jsObj 为桥连对象可随意设值
*/
mWebView.addJavascriptInterface(jsInterface, "jsObj");
/*
* Android(Java)访问js(HTML)端代码是通过loadUrl函数实现的,访问格式如:
* mWebView.loadUrl("javascript: showFromHtml()");
*/
mWebView.loadUrl("file:///android_asset/index.html");
} catch (Exception e) {
e.printStackTrace();
}
} private class JsInterface {
/**
* js中通过window.jsObj.HtmlcallJava2("参数") 可以调用此方法并且把js中input中的值作为参数传入,
* 但这是在点击js中的按钮得到的,若实现点击java中的按钮得到,需要方法 clickView(View v)
*
* @param param
*/
public void HtmlcallJava2(final String param) {
message = param;
String str = message;
StringTokenizer st = new StringTokenizer(str, ",;");
while (st.hasMoreTokens()) {
for (int i = 0; i < params.length; i++) {
params[i] = st.nextToken();
System.out.println(params[i]);
}
}
Toast.makeText(JSAndroidActivity.this, param, Toast.LENGTH_SHORT)
.show();
}
} /**
* button的点击事件
*
* @param v
*/
public void clickView(View v) {
runOnUiThread(new Runnable() {
@Override
public void run() {
/**
* 调用js中的方法实现点击java中的按钮得到js中input的值
*/
mWebView.loadUrl("javascript: showHtmlcallJava2()");
}
});
}
}
希望给大家带来帮助,谢谢!