新版PhoneGap插件开发入门实例(android)

来源:互联网 发布:it培训 编辑:程序博客网 时间:2024/06/05 10:09

最近看了一下PhoneGap,学习做一个插件,看了网上N多例子,都似乎没有交待清楚,自己摸索这做一个,在此记录下来,以后忘记了也可以看看,呵呵。

我用的是cordova 2.8.1,本来想用2.9的,可是用node.js硬是没有安装成功(自己人品问题?)。

好了,现在开始了:

第一步,写JAVA文件:

package com.example.plugins;import org.apache.cordova.api.CallbackContext;import org.apache.cordova.api.CordovaPlugin;import org.json.JSONArray;import org.json.JSONException;
//注意这里继承的是 CordovaPlugin 不是Plugin(这个被抛弃了)public class HelloPlugin extends CordovaPlugin {public static final String ACTION = "say";  @Overridepublic boolean execute(String action, JSONArray args,CallbackContext callbackContext) throws JSONException {// TODO Auto-generated method stub//return super.execute(action, args, callbackContext);if(action.equals(ACTION)){if(args.length()<2){callbackContext.error("参数错误");return false;}String pone=args.getString(0);String ptwo=args.getString(1);callbackContext.success(pone +" 对着 "+ ptwo+" 说:hello");return true;}else{callbackContext.error("action 参数错误");return false;}}}


第二步:注册插件

在res/xml/config.xml 中的<plugins>中加入,如下

    <plugins>      <!-- 这里加入刚才做的插件  name="HelloPlugin" 这个是注册插件的名称,在JS中需要用到 --->         <plugin  name="HelloPlugin" value="com.zhi.plugins.HelloPlugin"/>    </plugins>


第三步:在页面中使用插件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script  language="javascript" src="cordova-2.8.1.js" ></script><script language="javascript">//使用插件sayHellow,这里没有做HelloPlugin.js,而是直接用cordova.exec,为的是更简单明了function onSuccess(data){alert(data);}function onFailure(data){alert(data);}function hello(){var pone="a";var ptwo="b";          // 成功时回调, 失败时回调 , 注册的插件名称,  action,   参数(JSONArray)  cordova.exec(onSuccess,  onFailure,  "HelloPlugin",    "say",    [pone,ptwo]      );}</script><title>无标题文档</title></head><body>  <input type="button" value="test plugin" onclick="hello()" /></body></html>


完工,就这么简单



0 0
原创粉丝点击