Phonegap android 向其他应用程序用户发送通知

Phonegap android to send notification to other app uers

本文关键字:通知 用户 应用程序 android 其他 Phonegap      更新时间:2023-09-26

我有一个由我的同事开发的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();   

客户端代码:(拼音(

<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);
  }
};

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

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

您还可以使用Streethawk标记用户(例如管理员用户或普通用户(,并可以管理您的推送消息