根据官方文档(3.4.0)的插件开发指南:
http://docs.phonegap.com/en/3.4.0/guide_hybrid_plugins_index.md.html#Plugin%20Development%20Guide
http://docs.phonegap.com/en/3.4.0/guide_platforms_android_plugin.md.html#Android%20Plugins
该插件的功能就是接收页面发过来的一个字符串,并将字符串原样返回。
1,直接在android工程中添加一个插件包
在项目名称上点击右键,弹出菜单:new->package,Name填写包的名称:org.apache.cordova.plugin
2,编写插件代码
在新建出来的包上点击右键,弹出菜单:new->file,File Name填写:Echo.java,文件内容为:
package org.apache.cordova.plugin;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This class echoes a string called from JavaScript.
*/
public class Echo extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("echo")) {
String message = args.getString(0);
this.echo(message, callbackContext);
return true;
}
return false;
}
private void echo(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
}
3,配置项目的config.xml
config.xml位于res/xml下,在文件中增加以下内容:
<feature name="Echo">
<param name="android-package" value="org.apache.cordova.plugin.Echo"/>
</feature>
这里feature的name就是我们下面使用javascript调用时指定的名称,需要一致就行。org.apache.cordova.plugin.Echo就是包中的类名。
4,在页面中编写js代码来调用插件
cordova.exec(
function(echoValue){//成功时调用的函数
alert(echoValue);
},
function(err) {//失败时调用的函数
alert(err);
},
"Echo", "echo", //对应插件中的类和方法名
["send to native"]);//发到插件中的参数
出来就是这么一个效果: