最近项目中涉及到Android中的网络通信与交互、html5等相关内容,由于之前没仔细研究过,在这里总结一下,下面是JavaScript与Java相互调用的一个小例子,废话不多说,直接上代码:
<html>
<meta http-equiv="Content-Type" content="text/html;charset=GBK">
<head>
<script type="text/javascript">
function ok() {
window.player.playOk();
}
function wrong() {
window.player.playWrong();
}
function show_alert() {
alert("这是一个警告!")
}
function show_confirm() {
var v = confirm("确定你是个好人?")
if (v == true) {
alert("你选择了是!");
} else {
alert("你选择了否!");
}
}
function disp_prompt() {
var name = prompt("请输入您的名字", "Jerome")
if (name != null && name != "") {
document.getElementById("content").innerHTML = "你好!" + name;
}
}
function java_call() {
document.getElementById("content").innerHTML = "Java代码调用你了";
}
</script>
</head>
<body>
<input type="button" οnclick="ok()" value="OK" />
<br />
<input type="button" οnclick="wrong()" value="Warning">
<br />
<input type="button" οnclick="show_alert()" value="警告">
<br />
<input type="button" οnclick="show_confirm()" value="删除">
<br />
<input type="button" οnclick="disp_prompt()" value="显示提示框" />
<br />
<p id="content"></p>
</body>
</html>
这是html的代码,不接触web前段,js都不怎么会写了,简单的函数凑合用了,嘿嘿。
package com.example.jsjava;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;
/**
*
* ClassName:MainActivity
*
* @author Jerome Song
* @version
* @since Ver 1.1
* @Date 2013 2013-5-17 下午11:33:05
*
* @see
*/
public class MainActivity extends Activity {
private WebView webview = null;
private MediaPlayer player;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = new MediaPlayer();
initWebView();
}
private void initWebView() {
webview = (WebView) super.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true); // 启用JavaScript
webview.getSettings().setBuiltInZoomControls(true); // 控制页面缩放
webview.addJavascriptInterface(new PlayerMethod(), "player");// 添加Js函数调用接口
webview.setWebChromeClient(new WebChromeClient() {
@Override
// 弹出警告框操作
public boolean onJsAlert(WebView view, String url, String message,
final JsResult result) {
Dialog dialog = new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
result.cancel();
// 这里我们通过Webview.loadUrl()方法去调用js中的函数
webview.loadUrl("javascript:java_call()");
}
}).create();
dialog.setCancelable(false);// 避免点Back取消,那样js接收不到任何返回信息
dialog.show();
return true;
}
//
@Override
// 弹出确认框操作
public boolean onJsConfirm(WebView view, String url,
String message, final JsResult result) {
Dialog dialog = new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.stat_sys_warning)
.setMessage(message)
.setPositiveButton("是",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
result.confirm();
}
})
.setNegativeButton("否",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
result.cancel();
}
}).create();
dialog.setCancelable(false);
dialog.show();
return true;
}
// 提示
@Override
public boolean onJsPrompt(WebView view, String url, String message,
String defaultValue, final JsPromptResult result) {
final EditText text = new EditText(MainActivity.this);
text.setHint(defaultValue);
Dialog dialog = new AlertDialog.Builder(MainActivity.this)
.setTitle(message).setView(text)
.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
result.confirm(text.getText().toString());
}
}).setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
result.cancel();
}
}).create();
dialog.setCancelable(false);
dialog.show();
return true;
}
});
webview.loadUrl("file:///android_asset/html/play_js.html");
}
class PlayerMethod {
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
try {
if (msg.what == 1) {
play("ok.mp3");
} else {
play("wrong.mp3");
}
} catch (IOException e) {
e.printStackTrace();
}
};
};
AssetManager asm = getResources().getAssets();
public void playOk() throws IllegalArgumentException,
IllegalStateException, IOException {
handler.sendEmptyMessage(1);
}
public void playWrong() throws IOException {
handler.sendEmptyMessage(0);
}
private void play(String fileName) throws IOException {
if (player.isPlaying()) {
player.stop();
}
player.reset();
AssetFileDescriptor afd = asm.openFd(fileName);
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
afd.getLength());
player.prepare();
player.start();
}
}
}
有不对的地方希望大家能给予批评指正,多多交流,谢谢。
源码地址:http://download.csdn.net/detail/songzhiyong1121/5400403