您的位置:首页 > 编程语言 > Java开发

Cordova(PhoneGap)与Java进行通信

2014-12-26 00:00 453 查看
摘要: Cordova(PhoneGap)与Java进行通信

首先来看整个项目的结构:

图暂时找不到了,唉!

在assert/plugins创建一个js文件,我的是data.js,这个js的名称后面用到!
data.js内容如下:

/**
* 注意"org.apache.cordova.data"这里
* 此名称是后面在cordova_plugins.js中配置的id名称,必须唯一
*/
cordova.define("org.apache.cordova.data", function(require, exports, module) {

var exec = require('cordova/exec');

module.exports = {

send_data:function(datas){

exec(
//成功调用
function(params){
alert(params);
},

//失败调用
function(err){
alert(err)
},

//config.xml中的nama的值
"sendDataDemo" ,
//要调用的js的方法名称
"sendData",
//传递的参数,json格式
[datas]);
},

};

});

cordova_plugins.js :

cordova.define('cordova/plugin_list', function(require, exports, module) {module.exports = [
{
"file": "plugins/org.apache.cordova.dialogs/www/notification.js",
"id": "org.apache.cordova.dialogs.notification",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/org.apache.cordova.dialogs/www/android/notification.js",
"id": "org.apache.cordova.dialogs.notification_android",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/data.js",//引用js的目录
"id": "org.apache.cordova.data",//id号,唯一,此id号即是cordova.define(id,function(require, exports, module))
"merges": [//merges   代表你在 javascript中调用该接口的语句
"navigator.data"
]
}];module.exports.metadata = // TOP OF METADATA{
"org.apache.cordova.dialogs": "0.2.6",
"org.apache.cordova.camera": "0.2.8",
"org.apache.cordova.media-capture": "0.2.8",
"org.apache.cordova.file": "1.0.1",
"org.apache.cordova.data":"0.0.1"//这个版本随便写}// BOTTOM OF METADATA});

index.html内容:

<!DOCTYPE html><html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>

<script type="text/javascript" src="cordova.js"></script>

<script type="text/javascript" charset="utf-8">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}

// device APIs are available
//
function onDeviceReady() {

}

function showAlert () {
navigator.notification.alert(
'You are the winner!',  // message
alertDismissed,        // callback
'Game Over',           // title
'get it'               // buttonName
)
}

function alertDismissed () {

}

function showConfirm () {
navigator.notification.confirm(
'You are the winner!', // message
onConfirm,            // callback to invoke with index of button pressed
'Game Over',           // title
['Restart','Exit']// buttonLabels
)
}

function onConfirm (buttonIndex) {
alert('You selected button ' + buttonIndex);
}

function showPrompt () {
navigator.notification.prompt(
'Please enter your name',  // message
onPrompt,                  // callback to invoke
'Registration',            // title
['Ok','Exit'],             // buttonLabels
'Jane Doe'                 // defaultText
)
}

function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}

function sendData () {
navigator.data.send_data("test from js");
}

</script>

</head>
<body>

<p><a href="#" onclick="showAlert() ;return false">Alert</a></p>
<p><a href="#" onclick="showConfirm() ;return false">Confirm</a></p>
<p><a href="#" onclick="showPrompt() ;return false">Prompt</a></p>
<p><a href="#" onclick="sendData() ;return false">传数据到JAVA</a></p>

</body></html>

写一个Java类接受从JS传过来的数据内容如下:

package com.example.hello;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;import org.json.JSONArray;
import org.json.JSONException;
import android.widget.Toast;
public class SendDataDemo extends CordovaPlugin{

CallbackContext callbackContext ;

/**     * 此构造函数必须得写,而且不能格式不能这样     * SendDataDemo(){}     */
public SendDataDemo() {
}

@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {

this.callbackContext = callbackContext;
if ("sendData".equals(action)) {//sendData为index.html中的sendData方法名
String receive_msg = args.getString(0);

Toast.makeText(cordova.getActivity(), receive_msg, Toast.LENGTH_SHORT).show();

//接受成功后,回发数据到前台页面
callbackContext.success("message from java");

return true;
}

return false;
}}

最后重中之重是不要忘了配置config.xml 内容如下:

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.hello" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<preference name="loglevel" value="DEBUG" />
<feature name="App">
<param name="android-package" value="org.apache.cordova.App" />
</feature>
<feature name="Notification">
<param name="android-package" value="org.apache.cordova.dialogs.Notification" />
</feature>
<name>HelloWorld</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.    </description>
<author email="dev@cordova.apache.org" href="http://cordova.io">
Apache Cordova Team    </author>
<content src="index.html" />
<access origin="*" />
<feature name="Camera">
<param name="android-package" value="org.apache.cordova.camera.CameraLauncher" />
</feature>
<feature name="File">
<param name="android-package" value="org.apache.cordova.file.FileUtils" />
<param name="onload" value="true" />
</feature>
<feature name="Capture">
<param name="android-package" value="org.apache.cordova.mediacapture.Capture" />
</feature>

<!--sendDataDemo的名称与data.js中第三个参数一致-->
<feature name="sendDataDemo">
<!--value值为java类的包命+类名称-->
<param name="android-package" value="com.example.hello.SendDataDemo" />
</feature></widget>

附上源码:click me!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  phoneGap