GoogleCloudMessaging Plugin

Integrate with GCM Push to increase your users' engagement.

Increase Engagement

Push notifications are a direct channel to your app's users. Keep them happy and engaged with app updates, promotions, and more sent directly to their device.

Targeted Push Notifications

Send notifications to all users, a targeted segment or an individual user, thanks to push topics it has never been easier to send push notifications.

Overview

Push Notifications are a great way to keep users engaged and inform users about updates in your app.

In comparison to local notifications push notifications are triggered from a server-side logic. To make things easier Google Cloud Messaging provides a push backend for delivering notifications from a custom web-service.

Therefore push notifications are ideally suited for applications where you want to inform your users about externally triggered status updates, like sports live ticker apps, social messaging apps or any other app which should inform your users about an update.

Note: If you only need scheduled local notifications that don't require any external logic to be triggered have a look at our Notification Plugin.

Basic Usage

Push notifications can either be sent to a specific registered devices or targeted by subscribing to "topics".

To use push notifications in your app add the following item to your QML code:

 import QtQuick 2.1
 import VPlayPlugins 1.0

 GoogleCloudMessaging {

 }

Note: Additionally, you have to add a Google Services configuration file to your application. You can acquire those files here for Android and here for iOS. You can read more on setting up GoogleCloudMessaging for iOS here and Android here.

To subscribe to a specific topic add it to the list of topics:

 GoogleCloudMessaging {
   ...
   topics: [ "topic-1" ] // Subscribe to topic "topic-1"
   ...
 }

You can disable all push notification topics independent from the topics property by setting the enabled property to false:

 GoogleCloudMessaging {
   ...
   enabled: false // Disables all push notifications to the subscribed topics
   ...
 }

To handle an incoming push notification implement the GoogleCloudMessaging::notificationReceived signal handler:

 GoogleCloudMessaging {
   ...
   onNotificationReceived: {
     console.debug("Received notification payload is", JSON.stringify(data))
   }
   ...
 }

The data parameter is a map containing the JSON object content with all parameters of the push notification payload sent over Google Cloud Messaging.

The signal is emitted in following cases:

  • If the app is currently in the foreground, the signal is emitted immediately. However, there i no sound played and no banner is displayed.

    Note: On Android, you can use the GoogleCloudMessaging::processForegroundNotifications property to change this behavior. If GoogleCloudMessaging::processForegroundNotifications is set to false , notifications are handled the same way as if the app was in background.

  • If the app is in the background the system plays a short notification sound and displays a banner with your provided GoogleCloudMessaging alert payload. If the user then taps the notification the app goes to the foreground and the signal is emitted.

Testing Push Notifications

The GoogleCloudMessaging Plugin supports receiving simple text-based push messages or more advanced JSON payload messages, sent over the Google Cloud Messaging Push API.

To test push notifications on your device you can use any library or tool which supports HTTP POST requests. Here is an example how to send a push notification with the help of curl:

 curl --verbose \
 -X POST \
 -H "Authorization: key=<Your-Key>" \
 -H "Content-Type: application/json" \
 -d '{
   "to": "/topics/topic-1",
   "notification": {
     "title": "Json Title",
     "body": "Json Message"
   },
   "priority": "high"
 }' \
 https://gcm-http.googleapis.com/gcm/send

Note: To retrieve the key, you have to configure Google Cloud Messaging in the Google Dashboard. You can read more on setting up Google Cloud Messaging for iOS here and Android here.

You can define the text which should be shown within the notification in the notification block. The data block is provided within the GoogleCloudMessaging::notificationReceived handler.

Advanced Usages

Beside sending simple text messages within the alert block you can also send a more advanced payload for the following use-cases:

Localizing Push Messages

Sending push notifications to a localized app often means that you have to keep track of the language which is installed on the users' devices and send the notification payload depending on that settings.

To make your life easier it's also possible to send predefined localization keys, which are then replaced with localized strings bundled within your app.

To send a push notification with a localized key use a payload like the following, adding the body_loc_key parameter to the notification JSON block:

 curl --verbose \
 -X POST \
 -H "Authorization: key=<Your-Key>" \
 -H "Content-Type: application/json" \
 -d '{
   "to": "/topics/topic-1",
   "notification": {
     "body_loc_key": "NEW_HIGHSCORE"
   },
   "priority": "high"
 }' \
 https://gcm-http.googleapis.com/gcm/send

Localization for iOS

  1. Create a Localizable.strings file in a subfolder named <language>.lproj for each language you want to add, where <language> is a valid language abbreviation (e.g. en for English or de for German). Put all the language subfolders into your project's ios subfolder.
  2. Add the localization keys with their respective localized text in the following scheme to the Localizable.strings files:
     // file en.lproj/Localizable.strings
     "NEW_HIGHSCORE" = "New highscore";
    
     // file de.lproj/Localizable.strings
     "NEW_HIGHSCORE" = "Neuer Highscore";
  3. Add a block like the following, adapting to every language you want to add, to your .pro file to make sure that the Localizable.strings files are copied to your app bundle:
     ios {
       # Localization files, copied one by one
       locfile1.files = ios/en.lproj/Localizable.strings
       locfile1.path = en.lproj
       locfile2.files = ios/de.lproj/Localizable.strings
       locfile2.path = de.lproj
       QMAKE_BUNDLE_DATA += locfile1 locfile2
     }

Localization for Android

  1. Create or adapt a strings.xml file in a subfolder named values-<language> for each language you want to add, where <language> is a valid language abbreviation (e.g. en for English or de for German). Put all the language subfolders into your project's android/res subfolder.

    Note: You can also provide default texts in a strings.xml file in a subfolder named values (without the language postfix).

  2. Add the localization keys with their respective localized text in the following scheme to the strings.xml files:
     // file android/res/values-en/strings.xml
     <resources>
         <string name="NEW_HIGHSCORE">New highscore</string>
     </resources>
    
    
     // file android/res/values-de/strings.xml
     <resources>
         <string name="NEW_HIGHSCORE">Neuer Highscore</string>
     </resources>

    Note: If the translation can't be found in any of the strings.xml files the loc-key parameter is shown to the user in the notification.

Note: This approach is only suitable if all push notification texts are already defined at the time you're submitting your app to the app stores.

Navigating to a Specific Screen From Push Notifications

It's also possible to send additional key/values beside your alert payload. As an example you can send a screen code which you can navigate to when a user opens your app from a push notification. For this use case append additional keys to the JSOn payload. The following example defines an additional key named screen:

 curl --verbose \
 -X POST \
 -H "Authorization: key=<Your-Key>" \
 -H "Content-Type: application/json" \
 -d '{
   "to": "/topics/topic-1",
   "notification": {
     "title": "Look at this!"
   },
   "screen": "AwesomeScreen",
   "priority": "high"
 }' \
 https://gcm-http.googleapis.com/gcm/send

In your QML code you can then read the key by referencing it in the data parameter:

 GoogleCloudMessaging {
   ...
   onNotificationReceived: {
     // Get the screen key from the data payload
     var screen = data["screen"]

     // TODO: Navigate user to the appropriate screen
   }
   ...
 }

Note: Please keep in mind that the payload's length for push notifications is restricted by Apple's and Google's push notification payload. Therefore make sure that you keep your information reasonable small and postpone loading additional data after your user opens your app again.

Performing Background Downloads triggered by Push Notifications

If an app relies on displaying up-to-date information every time the app starts, it can be useful to prepare and cache new content for the user even while the app is not running in the foreground. The GoogleCloudMessaging Plugin makes tasks like this really easy.

It enables you to download string data such as JSON or XML, cache it in the background and then process it as soon as the user opens your app again.

The following properties and signals can be used for that:

Example

In this example, background messages are printed to the console. Up to 3 messages at a time will be stored.

 GoogleCloudMessaging {
   id: gcm

   topics: [ "background-topic-1" ]
   backgroundFetchUrl: "http://date.jsontest.com/"
   backgroundFetchEnabled: true
   backgroundFetchStackSize: 3

   onBackgroundFetchAvailable: {
     console.debug("New background data available:", content.length, "items:")
     for(var i = 0; i < content.length; i++) {
       console.debug(i + ":", content[i])
     }
   }
 }

Note: If you're using iOS 9 make sure that your GoogleCloudMessaging::backgroundFetchUrl meets Apple's App Transport Security (ATS) requirements.

Trigger a Background Download via Push

After you have added the required properties to your QML code you can test it by sending a push notification that contains a content-available key with an integer value of 1, like the message below:

Note: Make sure you have set up your Google Cloud Messaging Account properly and insert your GoogleCloudMessaging key into the message below.

 curl --verbose \
 -X POST \
 -H "Authorization: key=<Your-Key>" \
 -H "Content-Type: application/json" \
 -d '{
   "to": "/topics/background-topic-1",
   "data": {
     "content-available": 1
   },
   "priority": "high"
 }' \
 https://gcm-http.googleapis.com/gcm/send

Using URL Parameters

You can add parameters to the URL using %% placeholders. Placeholders will be replaced by parameters sent in the payload of your push notification. You can put an indefinite number of placeholders in your URL. Placeholders will be replaced in the order of the parameters you send.

Note: Make sure that the number of parameters and placeholders match. If you send too few parameters, the placeholders will be included in your URL. If you send too many parameters, not all of them will be used.

For example, the following push notification

 curl --verbose \
 -X POST \
 -H "Authorization: key=<Your-Key>" \
 -H "Content-Type: application/json" \
 -d '{
   "to": "/topics/background-topic-1",
   "data": {
     "content-available": 1,
      "params": [ "v", "net" ]
   },
   "priority": "high"
 }' \
 https://gcm-http.googleapis.com/gcm/send

and the following URL in your QML

 backgroundFetchUrl: "http://www.%%-play.%%/"

will result in the URL http://www.v-play.net/.

Available QML Items

GoogleCloudMessaging

Item provides remote push notifications for iOS & Android with the Google Cloud Messaging platform

Integration

To use the GoogleCloudMessaging plugin you need to add the platform-specific native libraries to your project, described here:

iOS Integration Steps

  1. Open the Google Developer Console and create your app here. Make sure the iOS Bundle ID you enter matches the one you used when creating your application.

  2. Take a note of your Server API Key. You will need it later for sending push messages.
  3. To receive push notifications on iOS, you also have to create a new developer and distribution push certificate (with a push-enabled iOS app id) here and upload it to Google Cloud Messaging.

  4. Proceed with the steps on the Google Cloud Messaging website and download the GoogleService-Info.plist.

  5. Put the GoogleService-Info.plist into your project's ios subfolder.
  6. Download our PluginDemo from https://github.com/v-play/PluginDemo/archive/master.zip and unzip it.
  7. Copy all files beginning with libGGL*, libGIP*, libGSDK*, libGTM*, libGcm* and libProtocolBuffers_external.a from the ios sub-folder to a sub-folder called ios within your project directory.
  8. Add the following lines of code to your .pro file:
     ios {
        VPLAY_PLUGINS += gcm
      }

Android Integration Steps

  1. Open the Google Developer Console and create your app here. Make sure the package name you enter matches the one you used when creating your application.

  2. Click the Enable Google Cloud Messaging button and take a note of your Server API Key. You will need it later for sending push messages.
  3. Proceed with the steps on the Google Cloud Messaging website and download the GoogleService-Info.json.

  4. Put the GoogleService-Info.json file into your project's android subfolder.
  5. Open your build.gradle file and add the following lines to the dependencies block within the buildscript block:
     dependencies {
         ...
         classpath 'com.google.gms:google-services:3.0.0'
     }
  6. Add the following lines to the second dependencies block:
     dependencies {
       compile 'net.vplay.plugins:plugin-gcm:2.+'
     }
  7. Add the following line at the end of your build.gradle file:
     apply plugin: 'com.google.gms.google-services'

    Note: If you did not create your project from any of our latest wizards, make sure that your project uses the Gradle Build System like described here.

  8. By default, the app's launcher icon will be used as notification icon within the status bar. Starting with Android 5, the OS forces notification icons to be all white when your app targets Android API 21 and above.

    It is therefore recommended to provide a distinct notification icon of size 24x24px (mdpi) with the name ic_stat_gcm_default.png within your Android app's resources.

Parse Plugin Migration Steps

Remove Parse dependencies

iOS
  1. Delete Parse.framework and {Bolts.framework} from the ios subfolder in your project directory
  2. Remove the following lines from your .pro file
     ios {
       # Parse framework
       LIBS += -F$$PWD/ios
       LIBS += -framework Bolts
       LIBS += -framework Parse
    
       # Parse dependencies
       LIBS += -framework AudioToolbox
       LIBS += -framework CFNetwork
       LIBS += -framework CoreGraphics
       LIBS += -framework CoreLocation
       LIBS += -framework QuartzCore
       LIBS += -framework Security
       LIBS += -framework StoreKit
       LIBS += -framework SystemConfiguration
       LIBS += -lz
       LIBS += -lsqlite3
     }
  3. If you added a custom Info.plist file, you can delete it from your ios subfolder and remove the QMAKE_INFO_PLIST = $$PWD/ios/Sample-Info.plist line from your .pro file.
Android
  1. Open your build.gradle file and remove the compile 'com.parse:parse-android:1.13.0' line
  2. Open your AndroidManifext.xml and remove all lines that were required for Parse within the <application> tag (see below)
     <service android:name="com.parse.PushService" />
    
     <receiver android:name="net.vplay.plugins.parse.ParseItem$Receiver"
         android:exported="false">
       <intent-filter>
         <action android:name="com.parse.push.intent.RECEIVE" />
         <action android:name="com.parse.push.intent.DELETE" />
         <action android:name="com.parse.push.intent.OPEN" />
         </intent-filter>
     </receiver>
    
     <receiver android:name="com.parse.GcmBroadcastReceiver"
         android:permission="com.google.android.c2dm.permission.SEND">
       <intent-filter>
         <action android:name="com.google.android.c2dm.intent.RECEIVE" />
         <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
    
         <!--
           IMPORTANT: Change "com.parse.starter" to match your app's package name.
         -->
         <category android:name="com.parse.starter" />
       </intent-filter>
     </receiver>
     <service android:name="net.vplay.plugins.parse.ParseDownloadService" />
    
     <!--
       IMPORTANT: Change "com.parse.starter.permission.C2D_MESSAGE" in the lines below
       to match your app's package name + ".permission.C2D_MESSAGE".
     -->
     <permission android:protectionLevel="signature"
         android:name="com.parse.starter.permission.C2D_MESSAGE" />
     <uses-permission android:name="com.parse.starter.permission.C2D_MESSAGE" />

Update QML

  1. In your QML, replace import VPlayPlugins.parse 1.0 with import VPlayPlugins 1.0
  2. Replace Parse with GoogleCloudMessaging in your code
  3. Remove senderID and applicationID from your former Parse code
  4. Generate a new License Key here and replace the licenseKey in your Parse item

    Example of a simple Parse implementation

     Parse {
       licenseKey: "<Your-License-Key"
    
       applicationId: "<Your-Application-Id"
       clientKey: "<Your-Client-Key"
    
       // Subscribe to channel "channel-1"
       channels: [ "channel-1" ]
    
       onNotificationReceived: {
         console.debug("Received notification with payload:", JSON.stringify(data))
       }
     }

    After applying the steps above, your implementation should look like this:

     GoogleCloudMessaging {
       licenseKey: "<Your-License-Key"
    
       // Subscribe to channel "channel-1"
       channels: [ "channel-1" ]
    
       onNotificationReceived: {
         console.debug("Received notification with payload:", JSON.stringify(data))
       }
     }

    Note: The GoogleCloudMessaging::channels property of the GoogleCloudMessaging Plugin is a convenience alias to the topics property to simplify the migration process.

  5. That's it, the QML API of the Parse and GoogleCloudMessaging item remains the same and all features of parse are supported

Integrate Google Cloud Messaging

After you have removed all dependencies to the Parse Plugin and updated your QML code, you can follow our integration guides for iOS and Android.

Update your Server-Side Code

Localizing Push-Messages

While you could send localized push messages by putting a loc-key property within the "alert" object, you now have to use the "body_loc_key" property provided by GCM.

Message Payloads

A typical push notification payload for Parse may have looked like the following:

 {
   "channels": [ "channel-1" ],
   "data": {
     "alert": "This is a V-Play Parse Plugin Test"
   }
 }

This message would be sent to all devices registered for channel-1. Google Cloud Messaging uses the same concept as channels, but refers to them as topics. By setting the "to" property in your JSON payload, you can specify the topic you want to send to. Additionally, you have to rename "data" to "notification" and "alert" to "body".

 {
   "to": "/topics/channel-1",
   "notification": {
     "body": "This is a V-Play GCM Plugin Test"
   },
   "priority": "high"
 }

Also, read Testing Push Notifications to find out how to send push messages using curl.

Read more on sending Google Cloud Messaging messages here.

Used Google Cloud Messaging SDK Versions

iOS GCM SDK 1.2.0
Android Google Play Services 10.0.1

Note: Other SDK versions higher than the stated ones might also be working but are not actively tested as of now.

See also Localizing Push Messages.

Voted #1 for:

  • Easiest to learn
  • Most time saving
  • Best support

Develop Cross-Platform Apps and Games 50% Faster!

  • Voted the best supported, most time-saving and easiest to learn cross-platform development tool
  • Based on the Qt framework, with native performance and appearance on all platforms including iOS and Android
  • Offers a variety of plugins to monetize, analyze and engage users
FREE!
create apps
create games
cross platform
native performance
3rd party services
game network
multiplayer
level editor
easiest to learn
biggest time saving
best support