Push notifications via PhoneGap on Android

Source: Internet
Author: User

Demand

Essential Knowledge

This article requires at least one intermediate level of PhoneGap development experience

must product

PhoneGap Build


User-level

All applicable


My last article was via PHONEGAP to be able to push notifications on Apple devices. In this article, I'll explain how to use PHONEGAP to push notifications on Android platforms. By contrast, I sent my notifications on Android devices for faster push speeds.


Google Cloud Messaging


Android notifications can be pushed through the googlecloud Messaging (GCM) service, which is similar to Apple's notification push service . They used to be support for C2DM (the framework for messaging between the cloud and devices), but now those APIs have been abandoned, and there is a Googlecloud message that provides more enhancement implementations that C2DM cannot provide. Through the cordova/phonegap plug-in can help you take advantage of Googlecloud messaging services.


The size of the message allocated to GCM's net load is 4KB (just string data), which is significantly larger than the 256 bits required by Apple push. here is an article about what these data types are supported by the messages sent. And I suggest you read about how to use this service before you build your application, because I have not discussed many of the details in this article. Some points I need to highlight in this article are:

    • GCM does not guarantee the distribution of messages or its order.
    • You don't need to run an android app on an android device to accept messages. In fact, it is broadcast through the network, when a message arrives, the system will wake up the Android app, of course, this will require you to set up the correct broadcast recipients and permissions for your application.
    • GCM does not provide any built-in user interface or message processing. GCM Simply passes the message data that has not been processed and sends it directly to the corresponding Android app, so you have all the right to data processing. For example, an app can send a notification, display a custom user interface, or silently synchronize data.

setting up how to push notifications

These steps will enable you to push notifications in your Android app:

1. use the command line tool or Eclipse to create a Androidcordova Project (we recommend using the command line)

2. download the GCM Cordova plugin .

3. Follow the steps in the plugin description:

    • Follow the instructions in the document to set up your GoogleCloudMessaging Account and note the item IDthat is located in the URL . For example, the following bold number is the one you need to send to the register () method:  






  1. <?xml:namespace prefix = "O"/>

  2. https://code.google.com/apis/console/?pli=1#project:824841663942
Copy Code

    • don't forget to replace the following code with the IDof your GCM project:






  1. Window. Gcm.register ("[your_sender_id]", "gcm_event", gcm_success, Gcm_fail);
Copy Code



    • contains the IDof your transmitter:






  1. Window. Gcm.register ("824841663942", "gcm_event", gcm_success, Gcm_fail);
Copy Code



4. When an app receives a message, it adds a handler for it to determine if it is open. For example, you might display a pop-up warning or a status bar notification.

Note: This plugin will handle GCM registrations and have a corresponding method to receive a message, but it does not actually respond to these notifications, which is what you need to add. You can also go deeper to read about how to learn how to add native code to generate a status bar notification.


If you need more information about creating a GCM project, there are some specific steps you can find here .


The PhoneGap plugin contains a simple project and has set registers for notification pushes, including changes to the configuration of the Androidmanifest.xml and plugins. And all you have to do is modify the Cordova_gcm_script.js file so that you can use the GCM sender/project ID in your register () function, which allows you to run it immediately or refer to the project as a reference and modify it to your own needs.


If you prefer to use eclipse to write your code, you can simply import the Android project that was created and include the plugin before you start your work.

1. Choose File | New | Project

2. Select "Android Project from Existing Code"

2013-5-14 16:04:00 Upload Download Attachments (23.84 KB)

Figure 1. Select "Android Project from Existing Code".


run the sample app

When you run the sample code in the plugin, it tries to automatically register your device. If the registration succeeds, you will see that the message contains a registration ID. (Look at the Regid string I circled below, which I ran in my Galaxy tablet)

2013-5-14 16:04:00 Upload Download Attachments (14.69 KB)

Figure 2: You'll see that the message contains a registered ID

Of course you should also be able to look at the output in your control Panel:




  1. 10-24 18:24:20.720:v/gcmreceiver:onregistered (21989): Registration ID arrived!
  2. 10-24 18:24:20.730:v/gcmreceiver:onregisterd (21989): {"Regid": " Apa91bfobawm7p3okxy2al8ri12vcjfus-gixwtoowxiobtspoe1h7fuh1vplbpgshdi_ FP7AIYVET-SSVGUERLWYA0CKPGHOXT1DAQYDSEFEM9ZTGZNRHQFV7KLCIVSIGYLPMLUTOPISHSSFSEDTCDFKOOZQNPSFG "," Event ":" Registered "}
  3. 10-24 18:24:20.730:v/gcmplugin:sendjavascript (21989): Javascript:gcm_event ({"Regid": " Apa91bfobawm7p3okxy2al8ri12vcjfus-gixwtoowxiobtspoe1h7fuh1vplbpgshdi_ FP7AIYVET-SSVGUERLWYA0CKPGHOXT1DAQYDSEFEM9ZTGZNRHQFV7KLCIVSIGYLPMLUTOPISHSSFSEDTCDFKOOZQNPSFG "," Event ":" Registered "})
Copy Code



Once you get the registration ID like the one shown above, you can start writing your server code. The following sections will explain how to use the node. JS code to send a message to your application. Alternatively, you can use Urban Airship or pushwoosh to send a notification. When you receive this message, you will see that the text shown in the following face is displayed on the screen:

2013-5-14 16:04:01 Upload Download Attachments (13.26 KB)

Figure 3. When you receive a message, you will see that the information is displayed.


This is although this plugin does not do any processing. In the next section, we'll show you a status bar notification when you get a message by adding some code.


Status bar Notifications


Because the plugin simply receives the message--whether or not your application is running--but even if the message arrives and does not do anything, you decide what response it should make. A common requirement is to display this message on a native status bar. On iOS, this process will be different and this notification will be displayed automatically. But on Android you need to write explicit code for it.


One option is to use the Cordova statusbarnotification plugin to achieve this effect. If you want to use a faster solution, you can simply add native Java code to your Gcmintentservice.javaonmessage () method, just like the code:


  1. String message = extras.getstring ("message");
  2. String title = extras.getstring ("title");
  3. Notification Notif = new Notification (Android. R.DRAWABLE.BTN_STAR_BIG_ON, message, System.currenttimemillis ());
  4. Notif.flags = Notification.flag_auto_cancel;
  5. Notif.defaults |= Notification.default_sound;
  6. Notif.defaults |= notification.default_vibrate;

  7. Intent notificationintent = new Intent (context, testsampleapp.class);
  8. Notificationintent.addflags (Intent.flag_activity_single_top);
  9. Pendingintent contentintent = pendingintent.getactivity (context, 0, notificationintent, 0);

  10. Notif.setlatesteventinfo (context, title, message, contentintent);
  11. String ns = Context.notification_service;
  12. Notificationmanager Mnotificationmanager = (Notificationmanager)
  13. Context.getsystemservice (NS);
  14. Mnotificationmanager.notify (1, Notif);
Copy Code


Also remember to add the following import so that the above code can be implemented:





  1. Import android.app.Notification;
  2. Import Android.app.NotificationManager;
  3. Import android.app.PendingIntent;
Copy Code



To make sure that you have used Youractivityclassname.class to replace the name of the subclass that inherits to Droidgap. For example, in the example project we call it mainactivity.


The above code will set a notification with a star image, along with the vibrate and default sound. This example is already running on my Android Galaxy tablet, as shown below (red circle marker)


2013-5-14 16:04:02 Upload Download Attachments (20.39 KB)

Figure 4: Status bar notification (includes star picture and vibrate, default sound)


When you click on this notification, the app will open and display the message it says is actually received.

2013-5-14 16:04:03 Upload Download Attachments (13.26 KB)

Figure 5. Clicking on that notification will trigger the application to open and display the message it received.


The status bar display differs depending on the device. On a typical Android phone, it will appear on top rather than on the bottom as I do.


through NODE-GCM to send a message


This is what makes Google Cloud messaging to send notifications via the node. JS Library. It is known as NODE-GCM. The code below is intended to allow my device to send a message.

I believe you noticed that I changed those keys. In the parameters that you send, use the ID that Google gave you when you applied for the Google Cloud Messaging service to specify your own API key. You will receive two API keys, a browser key and a server key, both of which may be used. If one of them doesn't work, try the other one. Also, when you register to use the above plugin, you also specify the value returned to your application. When you run your application and call the GCM register function, the registered ID will be displayed on your screen and on the console.





  1. var GCM = require (' NODE-GCM ');

  2. var message = new GCM. Message ();
  3. var sender = new Gcm.sender (' Aizasycdx8v9r0fmsasjoafff-p3fcfwxlvwkgl ');
  4. var registrationids = [];

  5. Message.adddata (' title ', ' My Game ');
  6. Message.adddata (' message ', ' Your turn!!!! ');
  7. Message.adddata (' msgcnt ', ' 1 ');
  8. Message.collapsekey = ' demo ';
  9. Message.delaywhileidle = true;
  10. Message.timetolive = 3;

  11. At least one token is Required-each app registers a different token
  12. Registrationids.push (' Apa91bfobawn7p3okxy2al8ri12vcjfus-gixwtoowxiobtspoe1h7fuh1vplbpgshdi_ Fp7aiyvet-ssvguerlwya0ckpghoxt1daqydsefem9ztgznrhqfv7klcivsigylpmlutopishssfsedtcdfkoozqnpgfs ');

  13. /**
  14. * Parameters:message-literal, Registrationids-array, No. of retries, callback-function
  15. */
  16. Sender.send (Message, registrationids, 4, function (result) {
  17. Console.log (result);
  18. });
  19. /** Use the following line if you want to send the message without retries
  20. Sender.sendnoretry (message, registrationids, function (result) {
  21. Console.log (result); });
  22. **/
Copy Code



To explicitly specify title and messagefor the title key and message key, the program's plug-in will look for it in Gcmintentservice.java:


  1. Bundle extras = Intent.getextras ();
  2. if (extras! = null) {
  3. try {
  4. String title = extras.getstring ("title");
  5. String message = extras.getstring ("message");
  6. ....
  7. }
  8. }
Copy Code



Collapse Key

According to the Android development documentation , when you define a folding key, it is only distributed to the last notification you receive and a given folding key, in order not to let the user be bothered by "excessive notifications" such as scores in sporting events.

2013-5-14 16:04:04 Upload Download Attachments (23.25 KB)

Figure 6. Specify a clear title and message for the title key and the message key. Notice the status bar notification (if accepted) that appears in the pop-up list, as shown in Figure 7

2013-5-14 16:04:04 Upload Download Attachments (23.86 KB)

Figure 7: Status bar notifications are displayed in the pop-up box


other plugins to choose from

Later on, I'll explain the information you need to use Cordova to push notifications on Android, and you might think of another plugin on GitHub. This plugin was designed to allow the pinch to take full advantage of Pushwoosh to push notifications, which I posted in my blog post,"using Pushwoosh allows you to simply push notifications through phonegap." The plugin API is similar to the Cordova notification push plugin on iOS, and interestingly, when I test it, my node. JS Service is still able to receive the pushed message even if it is not in the Pushwoosh server environment. In addition, I do not need to add any native Java code, can let the above status bar notification display.


Next Step

Following these connections you may need to click inside to see

    • use PhoneGap to push notifications through Pushwoosh.

    • Cordovapush Project --cross-platform push services based on NODE-APN and node-gcm .

    • Urban Airship Notification push Server --Fused PhoneGap



These can only be applied under the permission of creativecommons attribution-noncommercial-share alike 3.0 Unported License . Permissions are allowed only within the scope of the license, and the code for this example (including those used in the project) can be found on Adobe .

Original link: http://www.adobe.com/devnet/phonegap/articles/android-push-notifications-with-phonegap.html

Push notifications via PhoneGap on Android

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.