Learn what Felgo offers to help your business succeed. Start your free evaluation today! Felgo for Your Business

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.

Google Cloud Messaging Examples

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.

Plugin Demo App

To try the plugin or see an integration example have a look at the Felgo Plugin Demo app.

Please also have a look at our plugin example project on GitHub: https://github.com/FelgoSDK/PluginDemo.

Example 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
 import Felgo

 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: data => {
     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:
     if(CMAKE_SYSTEM_NAME STREQUAL "iOS")
         target_sources(TargetApp INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/ios/en.lproj/Localizable.strings")
         set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/ios/en.lproj/Localizable.strings" PROPERTIES
             MACOSX_PACKAGE_LOCATION "Resources/en.proj")
    
         target_sources(TargetApp INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/ios/de.lproj/Localizable.strings")
         set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/ios/de.lproj/Localizable.strings" PROPERTIES
             MACOSX_PACKAGE_LOCATION "Resources/de.lproj")
     endif()

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.

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: data => {
     // 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: content => {
     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.felgo.com/.

Available QML Items

GoogleCloudMessaging

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

Adding and Activating Plugins

How to Add a Felgo Plugin to your App or Game

When you create a new project, you can choose to add example plugin integrations as well. Open Qt Creator and choose “File / New File or Project”, then choose Single-Page Application in the Felgo Apps section or any other wizard. For Felgo Games, you can also find an own Game with Plugins project template as an own wizard.

Then select the platforms you want to run your application on. The plugins are available for both iOS & Android. There is a fallback functionality in place on Desktop platforms so your project still works when you call methods of the plugins. This allows you to do the main development on your PC, and for testing the plugin functionality you can run the project on iOS and Android.

After the Kit Selection, you can choose which of the plugins you’d like to add to your project:

Then complete the wizard, your project is now set up with all the correct plugin dependencies for Android & iOS automatically. This includes:

  • Setting up the .gradle file for Android.
  • Setting up the .plist file for iOS.
  • Setting up the CMakeLists.txt file to include the plugin libraries for iOS.

Note: Additional integration steps are still required for most plugins, for example to add the actual plugin libraries for iOS to your project. Please have a look at the integration steps described in the documentation for each of the used plugins.

If you have an existing Felgo application, follow these steps to include a plugin to your app or game:

In Qt Creator, select “File / New File or Project” and choose either Felgo Games or Felgo Apps from Files and Classes. Then select Felgo Plugin and press Choose.

You can now select the plugin you want to add:

The plugin item, which contains the chosen plugin and a short usage example, is now added to your project. To use the item in your project, simply perform these steps:

  • Include the created item (use the name you entered in the template before) in your main.qml file.
  • Modify the CMakeLists.txt file & .plist file for iOS usage. See the iOS integration guide of the chosen plugin for more information.
  • Modify the the .gradle file for Android usage. See the Android integration guide of the chosen plugin for more information.

Note: If you have an existing Qt application, you can also add Felgo Plugins to your app! See here how to do this.

Activating Plugins with a License Key

You can test all plugins as soon as the required integration steps and plugin configuration are completed.

However, the plugins are only available as Trial Versions if they are not activated with a valid license. When you are using unlicensed plugins, a dialog is shown and a watermark overlays your application to notify you about the testing state of the plugin.

All monetization plugins are free to use in all licenses, other plugins are only fully usable if you have purchased the Startup or Business license. To activate plugins and enable their full functionality it is required to create a license key. You can create such a key for your application using the license creation page.

This is how it works:

  • Choose the plugins you want to include in your license key:

  • Click on “Generate License Key” and set the app identifier & version code of your application. You can see that the AdMob plugin was enabled in this license key:

  • Copy the generated licenseKey to your GameWindow or App component.

  • You can now fully use the selected plugins!

Integration

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

Project Configuration

Add the following lines of code to your CMakeLists.txt file:

 set(FELGO_PLUGINS
    gcm
 )

Note: Make sure to declare the FELGO_PLUGINS before calling felgo_configure_executable, which links the required Frameworks based on your settings.

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/FelgoSDK/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. In addition to correctly setting up your Apple certificates and App Id for push notifications, it is important to also add the Push Notification entitlement for your iOS app.

    To activate the entitlement for your app with Xcode, open the *.xcodeproj in your build directory and activate Push Notifications in the capabilities tab.

    Note: It is required to again activate this setting whenever Qt Creator uses qmake to re-create the Xcode project each time you build your app.

    To avoid this, you can manually set an iOS entitlements file for your project in Qt Creator. Add the following settings to your CMakeLists.txt configuration to use a custom entitlements file:

     if(CMAKE_SYSTEM_NAME STREQUAL "iOS")
       set_target_properties(TargetApp PROPERTIES
           XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS
           "${CMAKE_CURRENT_SOURCE_DIR}/ios/TargetApp.entitlements")
    
       target_sources(TargetApp PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/ios/TargetApp.entitlements")
     endif()

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 {
       implementation 'com.felgo.plugins:plugin-gcm:4.+'
     }
  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.

Used Google Cloud Messaging SDK Versions

iOS GCM SDK 1.2.0
Android Google Play Services 11.8.0

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

Note: GCM does not work in combination with the Firebase Plugin at the moment. If you want to use Firebase with push notificiations, please send us an e-mail to request the feature.

Qt_Technology_Partner_RGB_475 Qt_Service_Partner_RGB_475_padded