레이블이 phonegap인 게시물을 표시합니다. 모든 게시물 표시
레이블이 phonegap인 게시물을 표시합니다. 모든 게시물 표시

20130715

Push Notifications Plugin Support added to PhoneGap Build


pgbI’m happy to post today there is now support for a generic push notifications plugin for PhoneGap Build. The new plugin is called PushPlugin and works for both iOS and Android push notifications. The iOS support is based on the Apple Push Notifications Service (APNS) and the Android support is based on Google Cloud Messaging (GCM). This has been a highly awaited need and I’m so glad I can finally share the good news.apple-push-notification-service
The details are all outlined well here with some sample code but I also created a quick sample project you can use for a reference that will work for both iOS and Android. I put the whole project including the XCode project in github, but you really only need the www folder for PhoneGap Build. There’s also a config.xml included you can use that includes the plugin reference there and is required for the native code to be added when built through PhoneGap Build. You will just need to change the application name, author and personal information in there to match your own :) You will also need to change the GCM id to match your sender id in the index.js file. Also, see my previous tutorials on push notifications for iOS and Android to get some sample code in PHP or node.js to send a push notification quickly for testing so you can see it all in action. Those posts used the previous plugins available however, you should use the most currently supported PushPlugin one now. Those posts also talk in-depth about signing up for GCM and how to use APNS as well.
I will also be holding two webinars on push notifications in February via Adobe TechLive, so come check those out for a walkthrough of how to get started with adding push notifications to your application for iOS and Android. I will talk more about the APIs and how to use them at that time as well. The PhoneGap Build team is busy working on additional support for more plugins. The currently supported ones can be found here: http://build.phonegap.com/docs/plugins.
The important parts of the code are outlined in the PushPlugin documentation but I’m also showing them from my sample here. It’s easier to see quickly how this new plugin could be used to register your device to receive notifications, and how you might handle the incoming message simply in the following:
    receivedEvent: function(id) {
        var pushNotification = window.plugins.pushNotification;
        if (device.platform == 'android' || device.platform == 'Android') {
            pushNotification.register(successHandler, errorHandler,{"senderID":"834841663931","ecb":"onNotificationGCM"});
        }
        else {
            pushNotification.register(this.tokenHandler,this.errorHandler,   {"badge":"true","sound":"true","alert":"true","ecb":"app.onNotificationAPN"});
        }
...
    }

   // iOS
    onNotificationAPN: function(event) {
        var pushNotification = window.plugins.pushNotification;
        console.log("Received a notification! " + event.alert);
        console.log("event sound " + event.sound);
        console.log("event badge " + event.badge);
        console.log("event " + event);
        if (event.alert) {
            navigator.notification.alert(event.alert);
        }
        if (event.badge) {
            console.log("Set badge on  " + pushNotification);
            pushNotification.setApplicationIconBadgeNumber(this.successHandler, event.badge);
        }
        if (event.sound) {
            var snd = new Media(event.sound);
            snd.play();
        }
    },
    // Android
    onNotificationGCM: function(e) {
        switch( e.event )
        {
            case 'registered':
                if ( e.regid.length > 0 )
                {
                    // Your GCM push server needs to know the regID before it can push to this device
                    // here is where you might want to send it the regID for later use.
                    alert('registration id = '+e.regid);
                }
            break;

            case 'message':
              // this is the actual push notification. its format depends on the data model
              // of the intermediary push server which must also be reflected in GCMIntentService.java
              alert('message = '+e.message+' msgcnt = '+e.msgcnt);
            break;

            case 'error':
              alert('GCM error = '+e.msg);
            break;

            default:
              alert('An unknown GCM event has occurred');
              break;
        }
    }
Please see the sample for the rest of the code.

Easy PhoneGap Push Notifications with Pushwoosh

I recently posted regarding the use of Push Notifications on both iOS and Androidwith PhoneGap. Both of those addressed sending push notifications from a general 3rd party server where you write the server side push code. However, there are many services out there you can leverage for sending push notifications as well and this post will address Pushwoosh in particular.
What’s nice about Pushwoosh is they have a free offering with basic push features to get you started and their service applies to multiple platforms in general as well as offering plugins and samples for PhoneGap applications targeting iOSAndroid, and Windows Phone 7. I noticed there also appears to be a plugin available and supported with PhoneGap Build. With all the PhoneGap support it seemed like a great service to blog about in addition to my recent push notification posts.

Overview

To use Pushwoosh, your PhoneGap application uses a PushNotification plugin to communicate with thePushwoosh APIs. You configure this plugin just like any other. For iOS you add it to the Cordova.plist and put the classes in the plugins folder. Below is an example of how the plugin looks in the Cordova.plist.
For Android you include the jars/java files and add the plugin to the list of plugins for your app (usually in config.xml or cordova.xml), for instance:
1
2
3
4
5
6
7
<plugins>
...
    <plugin name="Camera" value="org.apache.cordova.CameraLauncher"/>
    <plugin name="Contacts" value="org.apache.cordova.ContactManager"/>
    <plugin name="PushNotification" value="com.pushwoosh.test.plugin.pushnotifications.PushNotifications" onload="true"/>
...
</plugins>
For both platforms you’ll see a PushNotification.js file in the samples that has a set of calls for registering/unregistering for push notifications, as well as some other nice functions (sending current location, getting status etc), an excerpt is shown below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
...
    // Call this to register for push notifications and retreive a deviceToken
    PushNotification.prototype.registerDevice = function(config, success, fail) {
        cordova.exec(success, fail, "PushNotification", "registerDevice", config ? [config] : []);
    };
 
    // Call this to set tags for the device
    PushNotification.prototype.setTags = function(config, success, fail) {
        cordova.exec(success, fail, "PushNotification", "setTags", config ? [config] : []);
    };
 
    //Android Only----
    PushNotification.prototype.unregisterDevice = function(success, fail) {
        cordova.exec(success, fail, "PushNotification", "unregisterDevice", []);
    };
     
    PushNotification.prototype.startGeoPushes = function(success, fail) {
        cordova.exec(success, fail, "PushNotification", "startGeoPushes", []);
    };
 
    PushNotification.prototype.stopGeoPushes = function(success, fail) {
        cordova.exec(success, fail, "PushNotification", "stopGeoPushes", []);
    };
 
    //Android End----
     
    //iOS only----
    // Call this to send geo location for the device
    PushNotification.prototype.sendLocation = function(config, success, fail) {
        cordova.exec(success, fail, "PushNotification", "sendLocation", config ? [config] : []);
    };
..
Actual example usage of the PushNotification.js calls from JavaScript can be found under the Android Setup section further on in this post…

Getting Started

It will save you time to keep this link open in a browser for the Pushwoosh documentation reference.
  • Go to the Pushwoosh website, click on Start Now and sign up for a free account/
  • Once logged in, you will be taken to an applications page.
  • Create a new application and name it something meaningful to you. The name doesn’t have to match anything in particular, but you will use the associated app id (more to come on that).
  • Once created, configure the different platforms your application will run on. In my case I just configured iOS and Android for use with a PhoneGap application.
  • Android Configuration requires a Google Cloud Messaging API Key (see below for more setup details):
  • iOS Configuration requires your Apple certificate (.cer file) and key (.p12) if you’re using the manual and free service:
    There’s a guide to specifically getting the certificate and key set up through Apple here, or you can also visit my Push Notifications for iOS post.
    Be sure to use the exact app ID and package name chosen in the Apple Developer Portal in your iOS application in XCode as well. If you’ve ever done push notifications with iOS this should be a familiar process to you.
    If you have a premium account much of this manual configuration work can be done for you by just entering your Apple credentials in the Auto tab above.

Android Application Setup

Requirements

  • Google Cloud Messaging (GCM) Project Number
    It can be found in the URL after the #project, for example my GCM console URL is: https://code.google.com/apis/console/#project:824842663931, so my GCM project # is 824842663931.
  • Pushwoosh App ID
    This is found when you click on any of the applications defined within Pushwoosh, such as circled in the screenshot below:

Steps

  1. Download the Pushwoosh Android for PhoneGap sample either from the Pushwoosh applications page by hovering over the platform such as shown in the screenshot below, or go to this link to always grab the latest (be sure to pick the Android-PhoneGap link).
  2. Now follow these instructions to make your application work with Pushwoosh. Step 6 is where you need to use your own GCM project number and Pushwoosh app id as noted in the requirements. Here’s an example of some code to register the device and listen for push notifications:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    initPushwoosh: function() {
            var pushNotification = window.plugins.pushNotification;
        pushNotification.registerDevice({ projectid: "824842663931", appid : "A49E7-43076" },
                function(status) {
                    var pushToken = status;
                    console.warn('push token: ' + pushToken);
                },
                function(status) {
                    console.warn(JSON.stringify(['failed to register ', status]));
                }
        );
            document.addEventListener('push-notification', function(event) {           
                var title = event.notification.title;
                var userData = event.notification.userdata;
                if (typeof(userData) != "undefined") {
                   console.warn('user data: ' + JSON.stringify(userData));
                }   
                navigator.notification.alert(title);
        });
        },
By default you will not see notifications while the application is running or in the foreground. If you would like to still receive them while the application is open on Android, uncomment the following line in the PushNotification.java code:
1
2
//uncomment this code if you would like to receive the notifications in the app bypassing notification center if the app is in the foreground
cordova.getActivity().registerReceiver(mReceiver, intentFilter);

iOS Application Setup

  1. Retrieve your Pushwoosh App ID. As above, this is found when you click on any of the applications defined within Pushwoosh, such as circled in the screenshot below:
  2. Next simply follow the in-depth instructions here.

Other Cool Stuff

  • Stats
    The Pushwoosh web client also has a Stats page to help you determine how many messages you’ve pushed etc. You can also determine if the messages were successful or potential errors by combining data here along with the Pushes page. Here are a couple of screenshots from Stats andPushes pages respectively:

  • Advanced Notifications
    You can configure more advanced notifications that can have the notification open a URL or custom page when clicked containing HTML content and images etc. You can also set a special sound for iOS and Android, a badge (iOS), and options in the advanced notifications options.
  • Here’s a screenshot of how you can use their website to create a new page to be shown upon notification click:
    And here it is when opened on iOS from clicking the notification:
  • Geozones
    You can set up locations as zones to automatically push messages to the device when it has entered that zone through their Geozones feature. This is very useful for geofencing type apps. More to come in a further blog post on that!
  • Tags
    Use their API’s for setting tags to identify different types of users or preferences etc. More information about Pushwoosh and using tags can be found here.
    The PhoneGap plugins for Pushwoosh include support for this as well :) .
  • Great Support
    I was very impressed with the support I received while trying out this service. They were quick to respond with meaningful information and went out of their way to add some additional code to aid in some specific testing I was doing to try out their geozones offering which I will be posting about specifically next.
  • New Features Coming…
    In my exchanges I was also informed of some cool new features in the works and big enhancements to their Stats and website overall so it definitely seems like a great option to check out! Keep up with the latest happenings on their blog here.

Pushwoosh Plans

Here’s a quick summary page of the options available through Pushwoosh currently:


Articles