如何在我的(Android)Phonegap项目中实施Urban Airship推送通知?

时间:2015-01-14 08:21:25

标签: javascript android cordova push-notification urbanairship.com

我正在尝试将Urban Airship的推送通知实施到我的Phonegap项目(Android)中。我已经尝试使用Urban Airship的操作指南来实现它。 如果有人可以使用纯Javascript发布示例,我会很高兴: - )。

    <!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>4-4-2 Push Notification</title>

    <link href="css/jquery.mobile-1.1.1.css" rel="stylesheet" type="text/css"/>

    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/jquery.mobile-1.1.1.js"></script>
    <script type="text/javascript" src="PushNotification.js"></script>

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript">


      var onDeviceReady = function() {
        alert("Device ready!")

        // Incoming message callback
        var handleIncomingPush = function(event) {
          if(event.message) {
            alert("Incoming push: " + event.message)
          } else {
            alert("No incoming message")
          }
        }

        // Registration callback
        var onRegistration = function(event)  {
          if (!event.error) {
            alert("Reg Success: " + event.pushID)
            $('#id').text(event.pushID)
          } else {
            alert(event.error)
          }
        }

        // Register for any urban airship events
        document.addEventListener("urbanairship.registration", onRegistration, false)
        document.addEventListener("urbanairship.push", handleIncomingPush, false)

        // Handle resume
        document.addEventListener("resume", function() {
          alert("Device resume!")

          PushNotification.resetBadge()
          PushNotification.getIncoming(handleIncomingPush)

          // Reregister for urbanairship events if they were removed in pause event
          document.addEventListener("urbanairship.registration", onRegistration, false)
          document.addEventListener("urbanairship.push", handleIncomingPush, false)
        }, false)


        // Handle pause
        document.addEventListener("pause", function() {
          alert("Device pause!")

          // Remove urbanairship events.  Important on android to not receive push in the background.
          document.removeEventListener("urbanairship.registration", onRegistration, false)
          document.removeEventListener("urbanairship.push", handleIncomingPush, false)
        }, false)

        // Register for notification types
        PushNotification.registerForNotificationTypes(PushNotification.notificationType.badge | 
          PushNotification.notificationType.sound | 
          PushNotification.notificationType.alert)

        // Initiate the UI
        initiateUI()

        // Get any incoming push from device ready open
        PushNotification.getIncoming(handleIncomingPush)
      }

      // Initiates the UI and sets up any UI callbacks
      var initiateUI = function() {
        // Add tag to the UI
        var addTag = function(tag) {
          var $tag = $("<p>" + tag + "</p>")
          var $removeButton = $("<input type='button' class='removeTagButton' value='Remove' />")

          $tag.append($removeButton)
          $("#tags").prepend($tag)

          $removeButton.on("click", function(ev) {
            $tag.remove()

            // Remove the tag from the current list of tags
            PushNotification.getTags(function(obj) {
              alert("Removing tag: " + tag)
              obj.tags.splice(obj.tags.indexOf(tag), 1)
              PushNotification.setTags(obj.tags)
            })
          })
        }

        // Set the alias in the UI
        var setAlias = function(alias) {
          $("#alias").text(alias)
          $("#setAliasField").val("")
        }

        // Vibrate and Sound is only available on Android
        if (device.platform != "Android") {
          $("#soundEnabledSection").hide()
          $("#vibrateEnabledSection").hide()
        }

        // Update the interface with the current UA settings
        PushNotification.isPushEnabled(function(isEnabled) {
          $('#pushEnabled').val(isEnabled ? 'on' : 'off').change()
        })

        PushNotification.isSoundEnabled(function(isEnabled) {
          $('#soundEnabled').val(isEnabled ? 'on' : 'off').change()
        })

        PushNotification.isVibrateEnabled(function(isEnabled) {
          $('#vibrateEnabled').val(isEnabled ? 'on' : 'off').change()
        })

        PushNotification.isQuietTimeEnabled(function(isEnabled) {
          $('#quietTimeEnabled').val(isEnabled ? 'on' : 'off').change()
        })

        PushNotification.isLocationEnabled(function(isEnabled) {
          $('#locationEnabled').val(isEnabled ? 'on' : 'off').change()
        })

        PushNotification.getPushID(function(id) {
          if(id) {
             alert("Got push ID: " + id)
             $('#id').text(id)
          }
        })

        PushNotification.getAlias(function(alias) {
          if(alias) {
            alert("Got alias: " + alias)
            setAlias(alias)
          }
        })

        PushNotification.getTags(function(obj) {
          obj.tags.forEach(function(tag) {
            addTag(tag)
          })
        })

        PushNotification.getQuietTime(function(obj) {
          $("#startHour").val(obj.startHour)
          $("#startMinute").val(obj.startMinute)
          $("#endHour").val(obj.endHour)
          $("#endMinute").val(obj.endMinute)
        })

        // Set up change callbacks for the UI elements
        $('#pushEnabled').change(function() {
          if($('#pushEnabled').val() == "on") {
            PushNotification.enablePush()
          } else {
            PushNotification.disablePush()
          }
        })

        $('#locationEnabled').change(function() {
          if($('#locationEnabled').val() == "on") {
            PushNotification.enableLocation()
          } else {
            PushNotification.disableLocation()
          }
        })

        $('#soundEnabled').change(function() {
          var isEnabled = ($('#soundEnabled').val() == "on")
          PushNotification.setSoundEnabled(isEnabled)
        })

        $('#vibrateEnabled').change(function() {
          var isEnabled = ($('#vibrateEnabled').val() == "on")
          PushNotification.setVibrateEnabled(isEnabled)
        })

        $('#quietTimeEnabled').change(function() {
          var isEnabled = ($('#quietTimeEnabled').val() == "on")
          PushNotification.setQuietTimeEnabled(isEnabled)
        })

        $("#addTagButton").click(function(ev) {
          var tag = $("#addTagField").val()
          alert("Adding new tag: " + tag)

          PushNotification.getTags(function(obj) {
            if(obj.tags.indexOf(tag) == -1) {
              alert("Valid tag: " + tag)
              obj.tags = obj.tags.concat([tag])

              PushNotification.setTags(obj.tags, function() {
                addTag(tag)
                $("#addTagField").val('')
              })
            }
          })
        })

        $("#setQuietTimeButton").click(function(ev) {
          var startHour = parseInt($("#startHour").val())
          var startMinute = parseInt($("#startMinute").val())
          var endHour = parseInt($("#endHour").val())
          var endMinute = parseInt($("#endMinute").val())

          PushNotification.setQuietTime(startHour, startMinute, endHour, endMinute, function() {
            alert("Set quiet time from JS")
          })
        })

        $("#setAliasButton").click(function(ev) {
            alert('geklickt!');
          var alias = $("#setAliasField").val();
          PushNotification.setAlias(alias, function() {
            setAlias(alias);
            alert('alias gesetzt!');
          })
        })
      }

      document.addEventListener("deviceready", onDeviceReady, false)

    </script>
</head>
  <body onLoad="onDeviceReady()">
  <div data-role="page" id="page">

    <div data-role="header" class="ui-bar ui-bar-b">
      <center>
        <img border="0" src="img/logo.png" alt="Urban Airship" align="center" />
      </center>
    </div>

    <div data-role="content">
      <form>
        <div class="ui-body ui-body-b">

          <div data-role="fieldcontain">
            <label for="id">Identifier:</label><br />
            <span name="id" id="id" style="word-wrap: break-word;"></span>
            <center><h3>Push Settings</h3></center>
            <label>Alias: </label>
            <span name="alias" id="alias"></span><hr />
            <input type="text" name="setAliasField" id="setAliasField" style="width:96.5%;" />
            <input type="button" id="setAliasButton" value="Set alias" />
          </div>

          <div data-role="controlgroup">
            <label for="pushEnabled">Push Enabled</label>
            <select name="pushEnabled" id="pushEnabled" data-role="slider" data-theme="c" data-track-theme="c">
              <option value="off">Off</option>
              <option value="on">On</option>
            </select>
          </div>

          <div data-role="controlgroup">
            <span id="soundEnabledSection">
              <label for="soundEnabled">Sound Enabled</label>
              <select name="soundEnabled" id="soundEnabled" data-role="slider" data-theme="c" data-track-theme="c">
                <option value="off">Off</option>
                <option value="on">On</option>
              </select>
            </span>
          </div>

          <div data-role="controlgroup">
            <span id="vibrateEnabledSection">
              <label for="vibrateEnabled">Vibrate Enabled</label>
              <select name="vibrateEnabled" id="vibrateEnabled" data-role="slider" data-theme="c" data-track-theme="c">
                <option value="off">Off</option>
                <option value="on">On</option>
              </select>
            </span>
          </div>

          <div data-role="controlgroup">
            <label for="locationEnabled">Location Enabled</label>
            <select name="locationEnabled" id="locationEnabled" data-role="slider" data-theme="c" data-track-theme="c">
              <option value="off">Off</option>
              <option value="on">On</option>
            </select>
          </div>

          <div data-role="controlgroup">
            <label for="quietTimeEnabled">Quiet Time Enabled</label>
            <span id="quietTimeEnabledSection">
              <select name="quietTimeEnabled" id="quietTimeEnabled" data-role="slider" data-theme="c" data-track-theme="c">
                <option value="off">Off</option>
                <option value="on">On</option>
              </select>
            </span>
          </div>

          <div data-role="fieldcontain">
            <label for="startHour">Start Time (24h)</label>
            <input name="startHour" style="width: 3em; margin-left: -5px;" id="startHour" />:<input name="startMinute" style="width: 3em;" id="startMinute" /><br />
            <label for="startHour">End Time (24h)</label>
            <input name="endHour" style="width: 3em;" id="endHour" />:<input name="endMinute" style="width: 3em;" id="endMinute" />
            <input type="button" id="setQuietTimeButton" value="Set Quiet Time" />
          </div>

          <div data-role="fieldcontain">
            <input name="addTagField" id="addTagField" />
            <input type="button" id="addTagButton" value="Add tag" />
            <div id="tags"></div>
          </div>

        </div>
      </form>
    </div>

  </div>
</body>
</html>


<!-- config.xml -->
<?xml version='1.0' encoding='utf-8'?>
<widget id="ch.app24.test" version="1.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>4-4-2</name>
    <description>
        Integration der Push-Benachrichtigung.
    </description>
    <author email="************" href="***************">
        ************
    </author>
    <content src="index.html" />
    <gap:plugin name="com.urbanairship.phonegap.pushnotification" version="2.7.0" />
    <preference name="com.urbanairship.production_app_key" value="*************" />
    <preference name="com.urbanairship.production_app_secret" value="" />
    <preference name="com.urbanairship.development_app_key" value="***************" />
    <preference name="com.urbanairship.development_app_secret" value="***********" />
    <preference name="com.urbanairship.in_production" value="true" />
    <preference name="com.urbanairship.gcm_sender" value="*********" />
    <access origin="*" />
</widget>

1 个答案:

答案 0 :(得分:0)

您可以添加Urbanairship插件,其中包含以下链接:https://github.com/urbanairship/phonegap-ua-push

及以上插件也有一个例子,使用该示例,您可以在应用程序中轻松实现Urbanairship配置。

首先在你的应用程序中添加上面的插件,然后浏览主要主页上给出的一些基本代码片段。如果它没有帮助,请通过示例。

希望它有所帮助。

感谢。