Phonegap android向其他app用户发送通知

时间:2014-12-11 08:00:56

标签: javascript android cordova google-cloud-messaging

我有一个由我的同事开发的Android应用程序。该应用程序正在执行将一些文件上载到服务器的任务。我在应用程序中的一部分是我必须从服务器向所有或选定的应用程序用户发送通知消息。

在服务器端,我使用ASP.net向所有Android应用用户发送推送通知。我知道我将不得不使用GCM。我做了一些关于GCM的研究,并尝试了一些示例GCM应用程序,但我可以看到,要使用GCM服务,设备必须注册,这很好,但每次我关闭我的应用程序时,通知消息没有交付和应用程序崩溃。并且必须再次使用GCM注册我的设备才能发送通知。

如何在GCM中注册设备,直到卸载应用程序。怎么能实现呢?

我正在添加用于实现此目的的示例代码:

发送推送通知的服务器端代码:

        string regId = "APA9xxxxxxxxxxxxxxxxxxxxxPx69PQ";
        var applicationID = "AIxxxxxxxxxxxxxxxxxU";
        var SENDER_ID = "xxxxxxxxxxx";

        var value = "test message";
        WebRequest tRequest;
        tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send"); tRequest.Method = "post";
        tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
        tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
        //Data post to the Server
        string postData ="collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="+ value + "&data.time=" + System.DateTime.Now.ToString() +"&registration_id=" + regId + "";
        Console.WriteLine(postData);

        Byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        tRequest.ContentLength = byteArray.Length;

        Stream dataStream = tRequest.GetRequestStream();

        dataStream.Write(byteArray, 0, byteArray.Length);

        dataStream.Close();

        WebResponse tResponse = tRequest.GetResponse();

        dataStream = tResponse.GetResponseStream();

        StreamReader tReader = new StreamReader(dataStream);

        //Get response from GCM server.

        String sResponseFromServer = tReader.ReadToEnd();

        //Assigning GCM response to Label text
        Response.Write(sResponseFromServer);

        tReader.Close(); dataStream.Close();
        tResponse.Close();   

客户端代码:( Phonegap)

<html>
  <head>
    <meta charset="utf-8" />
    <title>PushNotificationSample</title>

    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

    <!-- Add stylesheets here. -->
  </head>
  <body>
    <!-- Add content here. -->
    <h1>PushNotificationSample</h1>

    <button id="register">Register for Push</button>
    <button id="unregister">Unregister from Push</button>
    <div>Status: <span id="status">not registered.</span></div>

    <script src="cordova.js"></script>
    <script src="PushNotification.js"></script>
    <script src="https://da189i1jfloii.cloudfront.net/js/kinvey-phonegap-1.1.4.min.js"></script>

    <!-- Add scripts here. -->
    <script src="js/index.js"></script>
    <script src="js/push.js"></script>
    <script>app.initialize();</script>
  </body>
</html>

JS档案

/**
 * Copyright 2014 Kinvey, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Push Notification namespace.
var push = {
  // The device ID. Set here because we need it in case of unregistering.
  deviceId: null,

  // Status DOM.
  status: document.getElementById('status'),

  /**
   * Initializes push functionality.
   */
  initialize: function() {

    // Check preconditions.
    if(null == window.plugins.pushNotification) {
      throw new Error('The PushPlugin is not installed.');
    }

    // Bind buttons.
    var register   = document.getElementById('register');
    var unregister = document.getElementById('unregister');
    register.addEventListener('click', push.register, false);
    unregister.addEventListener('click', push.unregister, false);
  },

  /**
   * Registers device for receiving Push Notifications.
   */
  register: function() {
    // Check preconditions.
    if(null != push.deviceId) {
      push.status.innerHTML = 'already registered.';
      return;
    }

    // Register for Android / iOS.
    var pushNotification = window.plugins.pushNotification;
    if('android' === device.platform.toLowerCase()) {// Android.
      pushNotification.register(push.successHandler, push.errorHandler, {
        ecb      : 'push.onNotificationGCM',
        senderID : '344215287060'// Google Project ID.
      });
    }
    else {// iOS.
      pushNotification.register(push.tokenHandler, push.errorHandler, {
        alert : 'true',
        badge : 'true',
        sound : 'true',
        ecb   : 'push.onNotificationAPN'
      });
    }
    push.status.innerHTML = 'registering…';
  },

  /**
   * General push success handler.
   */
  successHandler: function(result) {
    push.status.innerHTML = 'result: ' + result;
  },

  /**
   * General push error handler.
   */
  errorHandler: function(error) {
    push.status.innerHTML = 'error: ' + error;
  },

  /**
   * Token handler. Registers device with Kinvey.
   */
  tokenHandler: function(token) {
    push.deviceId = token;// Save.

    // Register device with Kinvey.
    Kinvey.Push.register(token).then(function() {
      push.status.innerHTML = 'registered.';
    }, push.errorHandler);
  },

  /**
   * Android notification handler.
   */
  onNotificationGCM: function(e) {
    if('registered' === e.event) {
      push.tokenHandler(e.regid);
    }
    else if('message' === e.event) {
      //navigator.notification.alert("hdgfdjf::"+e.payload.message);
      cordova.plugins.notification.badge.set(10);
    }
    else if('error' === e.event) {
      push.errorHandler(e.msg);
      navigator.notification.alert(e.msg);
    }
    else {// Unknown event.
      push.status.innerHTML = e;
    }
  },

  /**
   * iOS notification handler.
   */
  onNotificationAPN: function(event) {
    if(event.alert) {
      navigator.notification.alert(event.alert);
    }
    if(event.sound) {
      var snd = new Media(event.sound);
      snd.play();
    }
    if(event.badge) {
      window.plugins.pushNotification.setApplicationIconBadgeNumber(push.successHandler, push.errorHandler, event.badge)
    }
  },

  /**
   * Unregisters device from receiving Push Notifications.
   */
  unregister: function() {
    // Check preconditions.
    if(null == push.deviceId) {
      push.status.innerHTML = 'already unregistered.';
      return;
    }

    // Unregister.
    push.status.innerHTML = 'unregistering…';

    // Unregister device, and unregister from Kinvey.
    window.plugins.pushNotification.unregister(function() { });
    Kinvey.Push.unregister(push.deviceId).then(function() {
      push.deviceId = null;
      push.status.innerHTML = 'unregistered.';
    }, push.errorHandler);
  }
};

1 个答案:

答案 0 :(得分:1)

您可以使用Streethawk的Phonegap插件将推送消息发送到您的应用程序中。以下是Streethawk详细文档的链接。

http://api.streethawk.com/v1/docs/phonegap-introduction.html

您还可以使用Streethawk标记用户(简称管理员用户或普通用户)并管理推送消息