读书人

【Cordova2.9】 本地通报Notification

发布时间: 2013-07-09 09:50:47 作者: rapoo

【Cordova2.9】 本地通知Notification插件开发

本文目的:通过一个简单的本地通知插件开发来熟悉PhoneGap插件开发流程

PhoneGap(Cordova)是一个用来搭起js & html与原生Android沟通的桥梁,在phoneGap中,所有的js与原生android代码交互都通过插件机制完成。官方发布的phoneGap中已经提供了一些常用的插件,但这些插件在实际应用中还远远不够,仍然需要自行扩展大量的插件来满足应用的需求。在phoneGap中,开发一个插件是一件相当简单的事情,在本文提到的本地通知插件中,包含了一个send函数,用来调用Android原生的Notification在任务栏发出通知信息,该函数接收的JsonArray格式为[title,text],即通知的标题和内容信息。

后台插件类代码为:

public class NotificationPlugin extends CordovaPlugin {@Overridepublic boolean execute(String action, JSONArray args,CallbackContext callbackContext) throws JSONException {if ("send".equals(action)) {NotificationManager manager = (NotificationManager) this.cordova.getActivity().getSystemService(Context.NOTIFICATION_SERVICE);String title = args.getString(0);String text = args.getString(1);System.out.println("需要发送的信息..." + text);Notification notification = new Notification(R.drawable.icon, text,System.currentTimeMillis());notification.setLatestEventInfo(this.cordova.getActivity(), title,text, PendingIntent.getActivity(this.cordova.getActivity(),0, this.cordova.getActivity().getIntent(), 0));manager.notify(1, notification);return true;} else {return false;}}}

?将该插件注册给PhoneGap:

<feature name="Notify">  <param name="android-package" value="org.dylan.phonegap.plugins.NotificationPlugin"/></feature>

?前台的插件注入代码为:

(function(cordova) {var define = cordova.define;define("cordova/plugin/notify",function(require, exports, module){var argscheck = require('cordova/argscheck'),    exec = require('cordova/exec');exports.send=function(message,successCB,failCB){argscheck.checkArgs('AFF', 'notify.send', arguments);console.log("send notification["+message[1]+"]");        if (!message) {        failCB && failCB("请输入要通知的信息.");        } else {            exec(successCB, failCB, "Notify", "send", message);        }};});cordova.addConstructor(function() {if (!window.plugins) {window.plugins = {};}console.log("将插件注入cordova...");window.plugins.notify = cordova.require("cordova/plugin/notify");console.log("注入结果:" + typeof(window.plugins.notify));});})(cordova);

?在应用中使用该插件的示例如下:

var msg = ["新消息","消息内容"];window.plugins.notify.send(msg,function(){alert("成功");},function(msg){alert(msg || "失败");});

?

读书人网 >移动开发

热点推荐