读书人

Phonegap中自定义插件的应用

发布时间: 2012-06-30 17:20:12 作者: rapoo

Phonegap中自定义插件的使用

???????? 在phonegap中需要实现特定相关的功能,可能需要自定义扩展一下功能,那么扩展phonegap组件就成为了可能。

?

源代码结构图:

Phonegap中自定义插件的应用

?

?? 本文目的在于讲述怎么扩展一个phonegap组件以及实现。

?针对phonegap中activty扩展类:

package com.easyway.phonegap.datepicker;import com.phonegap.*;import android.os.Bundle;/** * 实现DroidGap的 *  * @Title:  * @Description: 实现 phonegap调用android中datepicker组件 * @Copyright:Copyright (c) 2011 * @Company:易程科技股份有限公司 * @Date:2012-5-4 * @author  longgangbai * @version 1.0 */public class PhonegapDatePluginActivity extends DroidGap {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //启动首页        super.loadUrl("file:///android_asset/www/index.html");    }}

?

?

插件实现类:

package com.easyway.phonegap.datepicker;import java.util.Calendar;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.app.DatePickerDialog;import android.app.DatePickerDialog.OnDateSetListener;import android.app.TimePickerDialog;import android.app.TimePickerDialog.OnTimeSetListener;import android.util.Log;import android.widget.DatePicker;import android.widget.TimePicker;import com.phonegap.api.PhonegapActivity;import com.phonegap.api.Plugin;import com.phonegap.api.PluginResult;import com.phonegap.api.PluginResult.Status;/** *  * 实现DroidGap的在phonegap中想采用类似android中时间选择器datepicker *  * @Title:  * @Description: 实现 phonegap调用android中datepicker组件 * @Copyright:Copyright (c) 2011 * @Company:易程科技股份有限公司 * @Date:2012-5-4 * @author  longgangbai * @version 1.0 */public class DatePickerPlugin extends Plugin {private static final String ACTION_DATE = "date";private static final String ACTION_TIME = "time";/* * 必须实现这个方法 * (non-Javadoc) *  * @see com.phonegap.api.Plugin#execute(java.lang.String, * org.json.JSONArray, java.lang.String) */@Overridepublic PluginResult execute(final String action, final JSONArray data,final String callBackId) {Log.d("DatePickerPlugin", "Plugin Called");PluginResult result = null;if (ACTION_DATE.equalsIgnoreCase(action)) {Log.d("DatePickerPluginListener execute", ACTION_DATE);this.showDatePicker(callBackId);final PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);r.setKeepCallback(true);return r;} else if (ACTION_TIME.equalsIgnoreCase(action)) {Log.d("DatePickerPluginListener execute", ACTION_TIME);this.showTimePicker(callBackId);final PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);r.setKeepCallback(true);return r;} else {result = new PluginResult(Status.INVALID_ACTION);Log.d("DatePickerPlugin", "Invalid action : " + action + " passed");}return result;}public synchronized void showTimePicker(final String callBackId) {final DatePickerPlugin datePickerPlugin = this;final PhonegapActivity currentCtx = ctx;final Runnable runnable = new Runnable() {public void run() {final TimePickerDialog tpd = new TimePickerDialog(currentCtx,new OnTimeSetListener() {public void onTimeSet(final TimePicker view,final int hourOfDay, final int minute) {final JSONObject userChoice = new JSONObject();try {userChoice.put("hour", hourOfDay);userChoice.put("min", minute);} catch (final JSONException jsonEx) {Log.e("showDatePicker","Got JSON Exception "+ jsonEx.getMessage());datePickerPlugin.error(new PluginResult(Status.JSON_EXCEPTION), callBackId);}datePickerPlugin.success(new PluginResult(PluginResult.Status.OK, userChoice),callBackId);}}, 1, 1, true);tpd.show();}};ctx.runOnUiThread(runnable);}public synchronized void showDatePicker(final String callBackId) {final DatePickerPlugin datePickerPlugin = this;final PhonegapActivity currentCtx = ctx;final Calendar c = Calendar.getInstance();final int mYear = c.get(Calendar.YEAR);final int mMonth = c.get(Calendar.MONTH);final int mDay = c.get(Calendar.DAY_OF_MONTH);final Runnable runnable = new Runnable() {public void run() {final DatePickerDialog dpd = new DatePickerDialog(currentCtx,new OnDateSetListener() {public void onDateSet(final DatePicker view,final int year, final int monthOfYear,final int dayOfMonth) {final JSONObject userChoice = new JSONObject();try {userChoice.put("year", year);userChoice.put("month", monthOfYear);userChoice.put("day", dayOfMonth);} catch (final JSONException jsonEx) {Log.e("showDatePicker","Got JSON Exception "+ jsonEx.getMessage());datePickerPlugin.error(new PluginResult(Status.JSON_EXCEPTION), callBackId);}datePickerPlugin.success(new PluginResult(PluginResult.Status.OK, userChoice),callBackId);}}, mYear, mMonth, mDay);dpd.show();}};ctx.runOnUiThread(runnable);}}

?

?

phonegap中plugin.xml中配置:

<?xml version="1.0" encoding="utf-8"?><plugins>    <plugin name="App" value="com.phonegap.App"/>    <plugin name="Geolocation" value="com.phonegap.GeoBroker"/>    <plugin name="Device" value="com.phonegap.Device"/>    <plugin name="Accelerometer" value="com.phonegap.AccelListener"/>    <plugin name="Compass" value="com.phonegap.CompassListener"/>    <plugin name="Media" value="com.phonegap.AudioHandler"/>    <plugin name="Camera" value="com.phonegap.CameraLauncher"/>    <plugin name="Contacts" value="com.phonegap.ContactManager"/>    <plugin name="Crypto" value="com.phonegap.CryptoHandler"/>    <plugin name="File" value="com.phonegap.FileUtils"/>    <plugin name="Network Status" value="com.phonegap.NetworkManager"/>    <plugin name="Notification" value="com.phonegap.Notification"/>    <plugin name="Storage" value="com.phonegap.Storage"/>    <plugin name="Temperature" value="com.phonegap.TempListener"/>    <plugin name="FileTransfer" value="com.phonegap.FileTransfer"/>    <plugin name="Capture" value="com.phonegap.Capture"/>    <plugin name="DatePickerPlugin" value="com.easyway.phonegap.datepicker.DatePickerPlugin"/></plugins>

?

插件对应的js的编写:

/** *   * @return Object literal singleton instance of DatePicker */var DatePicker = function() {};DatePicker.prototype.showDateOrTime = function(action,successCallback, failureCallback) { return PhoneGap.exec(  successCallback,    //Success callback from the plugin failureCallback,     //Error callback from the plugin 'DatePickerPlugin',  //Tell PhoneGap to run "DatePickerPlugin" Plugin action,              //Tell plugin, which action we want to perform []);        //Passing list of args to the plugin};/** * Enregistre une nouvelle bibliothèque de fonctions * auprès de PhoneGap **/PhoneGap.addConstructor(function() {    //如果不支持window.plugins,则创建并设置    if(!window.plugins){        window.plugins={};    }    window.plugins.datePickerPlugin=new DatePicker();    //向phonegap中注入插件相关的js    //Register the javascript plugin with PhoneGap    PhoneGap.addPlugin('datePickerPlugin', new DatePicker());    //phonegap中注入后台插件相关的java类  //Register the native class of plugin with PhoneGap    PluginManager.addService("DatePickerPlugin",                         "com.easyway.phonegap.datepicker.DatePickerPlugin");});

?

页面调用如下:

<!DOCTYPE HTML><html>  <head>    <meta name="viewport" content="width=320; user-scalable=no" />    <meta http-equiv="Content-type" content="text/html; charset=utf-8">    <title>Minimal AppLaud App</title>    <!-- 加载phonegap --><script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script><!-- 加载jquery --><script type="text/javascript" charset="utf-8" src="jquery.mobile/jquery-1.6.4.min"></script>    <!-- 加载jquerymobile --><script type="text/javascript" charset="utf-8" src="jquery.mobile/jquery.mobile-1.0.1.js"></script>    <!-- 加载自定义插件 -->    <script type="text/javascript" charset="utf-8" src="datePickerPlugin.js"></script><script type="text/javascript" charset="utf-8">           $(function(){     $("#datepicker").click(function(){         alert("0000000");          window.plugins.datePickerPlugin.showDateOrTime(        'date',        function(r){        document.getElementById("mydatetargetfield").value = r.day + "/" + r.month + "/" + r.year;        },        function(e){console.log(e);}        );     });     });</script>    </head>  <body  type="text" />   <input id="datepicker" type="button" value="时间选择器">  </body></html>

?

运行结果如下:

Phonegap中自定义插件的应用

?

源代码如下:

?

读书人网 >移动开发

热点推荐