PhoneGap/Cordova 应用通知

PhoneGap/Cordova app notifications

我是 PhoneGap/Cordova 的新手,我想在我的应用程序中添加一些通知。

  1. 推送通知 - 所以当新文章在应用程序上发布时,它会提醒用户。

  2. 本地通知 - 在设定的时间间隔(日期和时间)我可以提示用户关于我的应用程序的最新文章。

我进行了大量搜索,但无法找到可以直接导入项目然后修改的工作示例。

我试过以下插件但无法正常工作 https://github.com/katzer/cordova-plugin-local-notifications/

在项目中启用推送通知的步骤。

  1. 使用您的项目名称在 https://console.developers.google.com/ 中创建一个项目。

  2. 推送插件安装参考下面link https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/INSTALLATION.md

  3. 您的 push.js 文件中的代码 参考 https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md

    //代码:推送通知初始化和注册。

    if (!$window.PushNotification) {
    return;
    }
     var push = $window.PushNotification.init({
    android: {
        senderID: "Include your app sender ID XXXXXXX” 
    },
    ios: {
        alert: "true",
        badge: true,
        sound: 'false'
    },
    windows: {}
    });
    
    push.on('registration', function(data) {
    // this gives the unique deviceId, Or you can maintain array of deviceIds to register multiple devices.
    // if have specified single deviceId for example
    // save this deviceId in database for further operations, i.e. push messages to those ids.
    console.log(data.registrationId);
    });
    
    push.on('notification', function(data) {
    console.log(data.message);
    });
    
    push.on('error', function(e) {
    console.log(e.message);
    });
    push.off('notification', function(e) {
    console.log('off notify');
     });
    
  4. 发送推送通知有多种方式。在这里,我正在借助 gcm-server 进行通知。 您将需要安装 node-gcm。 创建一个新的 server.js 文件。

     var gcm = require('node-gcm');
     var message = new gcm.Message();
    //API Server Key
     var sender = new gcm.Sender('GIVE_YOUR_SERVER_API_KEY');
    var registrationIds = [];
    
     // Value the payload data to send...
    message.addData('message',"\u270C Peace, Love \u2764 and PhoneGap \u2706!");
    message.addData('title','Push Notification Sample' );
    message.addData('msgcnt','3'); // Shows up in the notification in the status bar
    message.addData('soundname','beep.wav'); //Sound to play 
    message.timeToLive = 3000;
    

    // 至少需要一个 reg id // 此处使用您在设备注册期间获得的注册 ID。

    registrationIds.push('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

    sender.send(消息,registrationIds,4,函数(结果){ console.log(结果); });

参考 http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/ 以清楚地了解通过 gcm-server 发送通知。这将在设备上显示通知。

您也可以使用 firebase 代替 gcm。

启用本地通知的步骤: 使用 cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications

将插件添加到您的项目

如linkhttps://github.com/katzer/cordova-plugin-local-notifications/

所示调用本地通知