UNPKG

phonegap-plugin-push

Version:
1,582 lines (1,300 loc) 74.2 kB
- [Overview](#overview) - [Foreground Events](#push-message-arrives-with-app-in-foreground) - [Background Events](#push-message-arrives-with-app-in-background) - [Tap Events](#user-clicks-on-notification-in-notification-center) - [Push Notification Message Format Overview](#push-notification-message-format-overview) - [Android Behaviour](#android-behaviour) - [Notification vs Data Payloads](#notification-vs-data-payloads) - [Localization](#localization) - [Images](#images) - [Sound](#sound) - [Stacking](#stacking) - [Inbox Stacking](#inbox-stacking) - [Action Buttons](#action-buttons) - [In Line Replies](#in-line-replies) - [Led in Notifications](#led-in-notifications) - [Vibration Pattern in Notifications](#vibration-pattern-in-notifications) - [Priority in Notifications](#priority-in-notifications) - [Picture Messages](#picture-messages) - [Background Notifications](#background-notifications) - [Use of content_available: true](#use-of-content_available-true) - [Caching](#caching) - [Chinese Android Phones](#chinese-android-phones) - [Application force closed](#application-force-closed) - [Visibility](#visibility-of-notifications) - [Ongoing Notifications](#ongoing-notifications) - [Badges](#badges) - [Support for Twilio Notify](#support-for-twilio-notify) - [Notification ID](#notification-id) - [Clicking Notification Does Not Bring App to Foreground](#clicking-notification-does-not-bring-app-to-foreground) - [Notification Channels](#notification-channels) - [iOS Behaviour](#ios-behaviour) - [Sound](#sound-1) - [Background Notifications](#background-notifications-1) - [VoIP Notifications](#voip-notifications) - [Action Buttons](#action-buttons-1) - [Action Buttons using FCM on iOS](#action-buttons-using-fcm-on-ios) - [FCM and Additional Data](#fcm-and-additional-data) - [FCM Payload Details](#fcm-payload-details) - [Windows Behaviour](#windows-behaviour) - [Notifications](#notifications) - [Setting Toast Capable Option for Windows](#setting-toast-capable-option-for-windows) - [Disabling the default processing of notifications by Windows](#disabling-the-default-processing-of-notifications-by-windows) - [Background Notifications](#background-notifications-2) # Overview The following flowchart attempts to give you a picture of what happens when a push message arrives on your device when you have an app using phonegap-plugin-push. ![push-flowchart](https://cloud.githubusercontent.com/assets/353180/15752003/36b80afa-28ba-11e6-818b-c6f5f2966d8f.png) ## Push message arrives with app in foreground - The push plugin receives the data from the remote push service and calls all of your `on('notification')` event handlers. - The message is _not_ displayed in the devices' notification center, as that is not normal behaviour for Android or iOS. ## Push message arrives with app in background - The push plugin receives the data from the remote push service and checks to see if there is a title or message in the received data object. If there is, then the message will be displayed in the devices notification center. - Then the push plugin checks to see if the app is running. If the user has killed the application, then no further processing of the push data will occur. - If the app is running in the background the push plugin then checks to see if `content-available` exists in the push data. - If `content-available` is set to `1`, then the plugin calls all of your `notification` event handlers. > Note: if `count` is given as `0` then all notifications are first cleared: always on Android, and if the `count` has gone down on iOS ## User clicks on notification in notification center - The app starts. - Then the plugin calls all of your `notification` event handlers. > Note: if the push payload contained `content-available: 1` then your `notification` event handler has already been called. It is up to you to handle the double event. Some ways to handle this _double_ event are: - don't include title/message in the push so it doesn't show up in the shader. - send two pushes, one to be processed in the background, and the other to show up in the shade. - include a unique ID in your push so you can check to see if you've already processed this event. # Push Notification Message Format Overview ## Android Message Format The JSON push message can contain the following fields, see https://developers.google.com/cloud-messaging/http-server-ref for a complete list. ```javascript var content = { priority: 'normal', // Valid values are "normal" and "high." data: { title: 'A short string describing the purpose of the notification', message: 'The text of the alert message', // "body" can be used as alias, is converted to "message" // localization of message is possible count: 5, // set the badge notification count at app icon sound: 'default', // play default sound ... or "soundname", see [Android Sound](#sound) section notId: 1, // unique ID for the message, used for grouping, see below 'content-available': '0', // configure background updates, see below custom_key1: 'value1', custom_key2: 'value2' } }; ``` ### Using AWS-SNS with GCM This is the JSON-encoded format you can e.g. send via AWS-SNS's web UI. Note, that the core message is json-encoded twice, so if we take the `content` from above you convert it this way ```javascript var gcm_message = JSON.stringify({ GCM: JSON.stringify(content), default: 'plain text message again' }); ``` ```json { "GCM": "{\"priority\":\"normal\",\"data\":{\"title\":\"A short string describing the purpose of the notification\",\"message\":\"The text of the alert message\",\"count\":5,\"sound\": \"default\",\"notId\":1,\"content-available\":\"0\",\"custom_key1\":\"value1\",\"custom_key2\":\"value2\"}}", "default": "plain text message again" } ``` ### Message Received in JavaScript This message is received in the `push.on("notification")` handler as follows. Note that the properties are "normalized" across platforms, so this is passed to the app on android: ```json { "count": "5", "message": "The text of the alert message", "sound": "default", "title": "A short string describing the purpose of the notification", "additionalData": { "custom_key1": "value1", "custom_key2": "value2", "notId": "1", "content_available": "0", "dismissed": false, "google.message_id": "...", "coldstart": false, "foreground": false } } ``` ## iOS Message Format The JSON message can contain the following fields, see [Apple developer docs](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html#//apple_ref/doc/uid/TP40008194-CH17-SW5) for a complete list ```json { "aps": { "alert": { // alternatively just a string: "Your Message", "title": "A short string describing the purpose of the notification", "body": "The text of the alert message", // localization of message is possible "launch-image": "The filename of an image file in the app bundle, with or without the filename extension. The image is used as the launch image when users tap the action button or move the action slider" }, "badge": 5, // Number to show at App icon "content-available": "0", // configure background updates, see below "category": "identifier", // Provide this key with a string value that represents the notification’s type "thread-id": "id", // Provide this key with a string value that represents the app-specific identifier for grouping notifications "sound": "default" // play default sound, or custom sound, see [iOS Sound](#sound-1) section }, "notId": 1, "custom_key1": "value1", "custom_key2": "value2" } ``` ### Using AWS-SNS with APNS This is the JSON-encoded format you can send via AWS-SNS's web UI: ```json { "APNS_SANDBOX": "{\"aps\":{\"alert\":{\"title\":\"A short string describing the purpose of the notification\",\"body\":\"The text of the alert message\",\"launch-image\":\"The filename of an image file in the app bundle, with or without the filename extension. The image is used as the launch image when users tap the action button or move the action slider\"},\"badge\":5,\"content-available\":\"0\",\"category\":\"identifier\",\"thread-id\":\"id\",\"sound\":\"default\"},\"notId\":1,\"custom_key1\":\"value1\",\"custom_key2\":\"value2\"}" } ``` Note: use "APNS" to send to an app signed and released to production or "APNS_SANDBOX" or to send to an app signed and released for development. You can include both keys (APNS and APNS_SANDBOX) in the message if you want to send both to apps signed for production and apps signed for development. ```json { "APNS": "{\"aps\":...}", "APNS_SANDBOX": "{\"aps\":...}", "default": "plain text message again" } ``` ### Message Received in JavaScript This message is received in the `push.on("notification")` handler as follows. Note that the properties are "normalized" accross platforms, so this is passed to the app on iOS: ```json { "count": 5, // "badge" is converted to "count" "message": "The text of the alert message", "sound": "default", "title": "A short string describing the purpose of the notification", "additionalData": { "category": "identifier", "coldstart": false, "foreground": false, "content-available": "0", "notId": 1, "custom_key1": "value1", "custom_key2": "value2", "launch-image": "The filename of an image file in the app bundle, with or without the filename extension. The image is used as the launch image when users tap the action button or move the action slider", "thread-id": "id" } } ``` # Android Behaviour ## Notification vs Data Payloads Notifications behave differently depending on the foreground/background state of the receiving app and the payload you send to the app. For instance if you send the following payload: ```json { "notification": { "title": "Test Notification", "body": "This offer expires at 11:30 or whatever", "notId": 10 } } ``` When your app is in the foreground, any `on('notification')` handlers you have registered will be called. However, if your app is in the background, the notification will show up in the system tray. Clicking on the notification in the system tray will start the app but your `on('notification')` handler will not be called as messages that have `notification` payloads will not cause the plugins `onMessageReceived` method to be called. If you send a payload with a mix of `notification` & `data` objects like this: ```json { "notification": { "title": "Test Notification", "body": "This offer expires at 11:30 or whatever", "notId": 10 }, "data": { "surveyID": "ewtawgreg-gragrag-rgarhthgbad" } } ``` When your app is in the foreground any `on('notification')` handlers you have registered will be called. If your app is in the background, the notification will show up in the system tray. Clicking on the notification in the system tray will start the app and your `on('notification')` handler will not be called as messages that have `notification` payloads will not cause the plugins `onMessageReceived` method to be called. My recommended format for your push payload when using this plugin (while it differs from Google's docs) works 100% of the time: ```json { "data": { "title": "Test Notification", "body": "This offer expires at 11:30 or whatever", "notId": 10, "surveyID": "ewtawgreg-gragrag-rgarhthgbad" } } ``` When your app is in the foreground any `on('notification')` handlers you have registered will be called. If your app is in the background, then the notification will show up in the system tray. Clicking on the notification in the system tray will start the app, and your `on('notification')` handler will be called with the following data: ```json { "message": "This offer expires at 11:30 or whatever", "title": "Test Notification", "additionalData": { "surveyID": "ewtawgreg-gragrag-rgarhthgbad" } } ``` ## Localization Plugin supported localization from resources for: title, message and summaryText. You may use simple link to locale constant. ```json { "registration_ids": ["my device id"], "data": { "title": { "locKey": "push_app_title" }, "message": "Simple non-localizable text for message!" } } ``` Or use localization with formatted constants. ```json { "registration_ids": ["my device id"], "data": { "title": { "locKey": "push_app_title" }, "message": { "locKey": "push_message_fox", "locData": ["fox", "dog"] } } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: { locKey: 'push_app_title' }, message: 'Simple non-localizable text for message!' // Constant with formatted params // message: {"locKey": "push_message_fox", "locData": ["fox", "dog"]}); } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` Localization must store in strings.xml ```xml <string name="push_app_title">@string/app_name</string> <string name="push_message_fox">The quick brown %1$s jumps over the lazy %2$s</string> <string name="push_summary_text">%%n%% new message(s)</string> ``` ## Images By default the icon displayed in your push notification will be your apps icon. So when you initialize the plugin like this: ```javascript const push = PushNotification.init({ android: {}, browser: { pushServiceURL: 'http://push.api.phonegap.com/v1/push' }, ios: { alert: 'true', badge: 'true', sound: 'true' }, windows: {} }); ``` The result will look much like this: ![2015-07-24 02 52 00](https://cloud.githubusercontent.com/assets/353180/8866899/2df00c3c-3190-11e5-8552-96201fb4424b.png) Note that the notification icon has gone from the default, rich, multicolored cordova icon, to a white-on-gray one. What's going on here? With Android now greatly using Material design since 5.0 (Lollipop), push notification icons are forced to be monochromatic - this can be difficult to diagnose, as a lot of icons just show as a white square if not properly designed. You should design one with these guidelines in mind: - 96x96 pixels - Transparent background - White foreground For more details, please read: - https://material.io/tools/icons - https://material.io/design/iconography/ **Note:** any color foreground will work - any non-transparent pixels are just rendered white. To specify an alternate icon and background color to be shown when receiving a push notification, use the following: ```javascript const push = PushNotification.init({ android: { icon: 'phonegap', iconColor: 'blue' }, browser: { pushServiceURL: 'http://push.api.phonegap.com/v1/push' }, ios: { alert: 'true', badge: 'true', sound: 'true' }, windows: {} }); ``` Where _icon_ is the name of an `.png` image file in the Android `res/drawable` folder. For example: `platforms/android/res/drawable/phonegap.png` You can use a `resource-file` tag to copy the image to the `res/drawable` folder like this: ```xml <resource-file src="res/icon/android/push/drawable-mdpi/icon.png" target="app/src/main/res/drawable-mdpi/icon.png" /> <resource-file src="res/icon/android/push/drawable-hdpi/icon.png" target="app/src/main/res/drawable-hdpi/icon.png" /> <resource-file src="res/icon/android/push/drawable-xhdpi/icon.png" target="app/src/main/res/drawable-xhdpi/icon.png" /> <resource-file src="res/icon/android/push/drawable-xxhdpi/icon.png" target="app/src/main/res/drawable-xxhdpi/icon.png" /> <resource-file src="res/icon/android/push/drawable-xxxhdpi/icon.png" target="app/src/main/res/drawable-xxxhdpi/icon.png" /> ``` `iconColor` is one of the supported formats #RRGGBB or #AARRGGBB or one of the following names: 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'. `iconColor` is supported on Android 5.0 and greater. Please follow the [Android icon design guidelines](https://www.google.com/design/spec/style/icons.html#) when creating your icon. ![2015-07-24 02 46 58](https://cloud.githubusercontent.com/assets/353180/8866902/2df3276e-3190-11e5-842a-c8cd95615ab0.png) Additionally, each push can include a large icon which is used to personalize each push. The location of the image may be one of three types. The first is the `res/drawable` folder in your app. This JSON is sent from FCM: ```javascript { "registration_ids": ["my device id"], "data": { "title": "Large Icon", "message": "Loaded from drawable folder", "image": "twitter" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Large Icon', message: 'Loaded from drawables folder.', image: 'twitter' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` Would look for the _twitter_ image in the `res/drawable` folder and produce the following notification. ![2015-07-24 02 34 41](https://cloud.githubusercontent.com/assets/353180/8866903/2df48028-3190-11e5-8176-fe8b3f7c5aab.png) Again you can use a `resource-file` tag to copy the image to the `res/drawable` folder like this: ```xml <resource-file src="res/icon/android/push/drawable-mdpi/twitter.png" target="app/src/main/res/drawable-mdpi/twitter.png" /> <resource-file src="res/icon/android/push/drawable-hdpi/twitter.png" target="app/src/main/res/drawable-hdpi/twitter.png" /> <resource-file src="res/icon/android/push/drawable-xhdpi/twitter.png" target="app/src/main/res/drawable-xhdpi/twitter.png" /> <resource-file src="res/icon/android/push/drawable-xxhdpi/twitter.png" target="app/src/main/res/drawable-xxhdpi/twitter.png" /> <resource-file src="res/icon/android/push/drawable-xxxhdpi/twitter.png" target="app/src/main/res/drawable-xxxhdpi/twitter.png" /> ``` The second is the _assets_ folder in your app. This JSON sent from FCM: ```json { "registration_ids": ["my device id"], "data": { "title": "Large Icon", "message": "Loaded from assets folder", "image": "www/image/logo.png" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Large Icon', message: 'Loaded from assets folder.', image: 'www/image/logo.png' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` Would look for the _logo.png_ file in the assets/www/img folder. Since your apps www folder gets copied into the Android assets folder it is an excellent spot to store the images without needing to write a hook to copy them to the `res/drawable` folder. It produces the following notification. ![2015-07-24 02 20 02](https://cloud.githubusercontent.com/assets/353180/8866901/2df19052-3190-11e5-8c16-a355c59209f3.png) The third is the remote _URL_. This JSON sent from FCM: ```json { "registration_ids": ["my device id"], "data": { "title": "Large Icon", "message": "Loaded from URL", "image": "https://dl.dropboxusercontent.com/u/887989/antshot.png" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Large Icon', message: 'Loaded from URL', image: 'https://dl.dropboxusercontent.com/u/887989/antshot.png' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` Produces the following notification. ![2015-07-24 02 17 55](https://cloud.githubusercontent.com/assets/353180/8866900/2df0ab06-3190-11e5-9a81-fdb85bb0f5a4.png) Finally, the Material UI guidelines recommend using a circular icon for the large icon if the subject of the image is a person. This JSON sent from FCM: ```json { "registration_ids": ["my device id"], "data": { "title": "Large Circular Icon", "message": "Loaded from URL", "image": "https://pbs.twimg.com/profile_images/837060031895896065/VHIQ4oUf_400x400.jpg", "image-type": "circle" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Large Circular Icon', message: 'Loaded from URL', image: 'https://pbs.twimg.com/profile_images/837060031895896065/VHIQ4oUf_400x400.jpg', 'image-type': 'circular' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` Produces the following notification. ![screenshot_20170308-214947](https://cloud.githubusercontent.com/assets/353180/23733917/902a4650-0449-11e7-924e-d45a38030c74.png) ## Sound For Android there are three special values for sound you can use. The first is `default` which will play the phones default notification sound. ```json { "registration_ids": ["my device id"], "data": { "title": "Default", "message": "Plays default notification sound", "soundname": "default" } } ``` Then second is `ringtone` which will play the phones default ringtone sound. ```json { "registration_ids": ["my device id"], "data": { "title": "Ringtone", "message": "Plays default ringtone sound", "soundname": "ringtone" } } ``` The third is the empty string which will cause for the playing of sound to be skipped. ```json { "registration_ids": ["my device id"], "data": { "title": "Silece", "message": "Skips playing any sound", "soundname": "" } } ``` In order for your your notification to play a custom sound you will need to add the files to your Android project's `res/raw` directory. The best way to do this is by using a `resource-file` tag in your `config.xml`. ```xml <resource-file src="assets/sound/test.mp3" target="app/src/main/res/raw/test.mp3" /> ``` Then send the follow JSON from FCM: ```json { "registration_ids": ["my device id"], "data": { "title": "Sound Test", "message": "Loaded res/raw", "soundname": "test" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Sound Test', message: 'Loaded res/raw', soundname: 'test' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` _Note:_ when you specify the custom sound file name omit the file's extension. ## Stacking By default when using this plugin on Android each notification that your app receives will replace the previous notification in the shade. If you want to see multiple notifications in the shade you will need to provide a notification ID as part of the push data sent to the app. For instance if you send: ```json { "registration_ids": ["my device id"], "data": { "title": "Test Push", "message": "Push number 1" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Test Push', message: 'Push number 1' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` Followed by: ```json { "registration_ids": ["my device id"], "data": { "title": "Test Push", "message": "Push number 2" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Test Push', message: 'Push number 2' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` You will only see "Push number 2" in the shade. However, if you send: ```json { "registration_ids": ["my device id"], "data": { "title": "Test Push", "message": "Push number 1", "notId": 1 } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Test Push', message: 'Push number 1', notId: 1 } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` and: ```json { "registration_ids": ["my device id"], "data": { "title": "Test Push", "message": "Push number 2", "notId": 2 } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Test Push', message: 'Push number 2', notId: 2 } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` You will see both "Push number 1" and "Push number 2" in the shade. ## Inbox Stacking A better alternative to stacking your notifications is to use the inbox style to have up to 8 lines of notification text in a single notification. If you send the following JSON from FCM you will see: ```json { "registration_ids": ["my device id"], "data": { "title": "My Title", "message": "My first message", "style": "inbox", "summaryText": "There are %n% notifications" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'My Title', message: 'My first message', style: 'inbox', summaryText: 'There are %n% notifications' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` It will produce a normal looking notification: ![2015-08-25 14 11 27](https://cloud.githubusercontent.com/assets/353180/9468840/c9c5d43a-4b11-11e5-814f-8dc995f47830.png) But, if you follow it up with subsequent notifications like: ```json { "registration_ids": ["my device id"], "data": { "title": "My Title", "message": "My second message", "style": "inbox", "summaryText": "There are %n% notifications" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'My Title', message: 'My second message', style: 'inbox', summaryText: 'There are %n% notifications' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` You will get an inbox view so you can display multiple notifications in a single panel. ![2015-08-25 14 01 35](https://cloud.githubusercontent.com/assets/353180/9468727/2d658bee-4b11-11e5-90fa-248d54c8f3f6.png) If you use `%n%` in the `summaryText` of the JSON coming down from FCM it will be replaced by the number of messages that are currently in the queue. ## Action Buttons Your notification can include a maximum of three action buttons. You register the event callback name for each of your actions, then when a user clicks on one of notification's buttons, the event corresponding to that button is fired and the listener you have registered is invoked. For instance, here is a setup with two actions `emailGuests` and `snooze`. ```javascript const push = PushNotification.init({ android: {} }); // data contains the push payload just like a notification event push.on('emailGuests', data => { console.log('I should email my guests'); }); push.on('snooze', data => { console.log('Remind me later'); }); ``` If you wish to include an icon along with the button name, they must be placed in the `res/drawable` directory of your Android project. Then you can send the following JSON from FCM: ```json { "registration_ids": ["my device id"], "data": { "title": "AUX Scrum", "message": "Scrum: Daily touchbase @ 10am Please be on time so we can cover everything on the agenda.", "actions": [ { "icon": "emailGuests", "title": "EMAIL GUESTS", "callback": "emailGuests", "foreground": true }, { "icon": "snooze", "title": "SNOOZE", "callback": "snooze", "foreground": false } ] } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'AUX Scrum', message: 'Scrum: Daily touchbase @ 10am Please be on time so we can cover everything on the agenda.', actions: [ { icon: 'emailGuests', title: 'EMAIL GUESTS', callback: 'emailGuests', foreground: true }, { icon: 'snooze', title: 'SNOOZE', callback: 'snooze', foreground: false } ] } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` This will produce the following notification in your tray: ![action_combo](https://cloud.githubusercontent.com/assets/353180/9313435/02554d2a-44f1-11e5-8cd9-0aadd1e02b18.png) If your user clicks on the main body of the notification, then your app will be opened. However, if they click on either of the action buttons the app will open (or start) and the specified event will be triggered with the callback name. In this case it is `emailGuests` and `snooze`, respectively. If you set the `foreground` property to `true`, the app will be brought to the front, if `foreground` is `false` then the callback is run without the app being brought to the foreground. ### In Line Replies Android N introduces a new capability for push notifications, the in line reply text field. If you wish to get some text data from the user when the action button is called send the following type of payload. Your notification can include action buttons. If you wish to include an icon along with the button name they must be placed in the `res/drawable` directory of your Android project. Then you can send the following JSON from FCM: ```json { "registration_ids": ["my device id"], "data": { "title": "AUX Scrum", "message": "Scrum: Daily touchbase @ 10am Please be on time so we can cover everything on the agenda.", "actions": [ { "icon": "emailGuests", "title": "EMAIL GUESTS", "callback": "emailGuests", "foreground": false, "inline": true, "replyLabel": "Enter your reply here" }, { "icon": "snooze", "title": "SNOOZE", "callback": "snooze", "foreground": false } ] } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'AUX Scrum', message: 'Scrum: Daily touchbase @ 10am Please be on time so we can cover everything on the agenda.', actions: [ { icon: 'emailGuests', title: 'EMAIL GUESTS', callback: 'emailGuests', foreground: false, inline: true, replyLabel: 'Enter your reply here' }, { icon: 'snooze', title: 'SNOOZE', callback: 'snooze', foreground: false } ] } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` when the user clicks on the Email Guests button whilst using Android N and greater, they will see the following: ![inline_reply](https://cloud.githubusercontent.com/assets/353180/17107608/f35c208e-525d-11e6-94de-a3590c6f500d.png) Then your app's `on('notification')` event handler will be called without the app being brought to the foreground and the event data would be: ```json { "title": "AUX Scrum", "message": "Scrum: Daily touchbase @ 10am Please be on time so we can cover everything on the agenda.", "additionalData": { "inlineReply": "Sounds good", "actions": [ { "inline": true, "callback": "accept", "foreground": false, "title": "Accept" }, { "icon": "snooze", "callback": "reject", "foreground": false, "title": "Reject" } ], "actionCallback": "accept", "coldstart": false, "collapse_key": "do_not_collapse", "foreground": false } } ``` and the text data that the user typed would be located in `data.additionalData.inlineReply`. **Note:** On Android M and earlier the above in line behavior is not supported. As a fallback when `inline` is set to `true` the `foreground` setting will be changed to the default `true` setting. This allows your app to be launched from a closed state into the foreground where any behavior desired as a result of the user selecting the in line reply action button can be handled through the associated `callback`. #### Attributes | Attribute | Type | Default | Description | | ------------ | --------- | ----------------------- | -------------------------------------------------------------------------------------------------------------- | | `icon` | `string` | | Optional. The name of a drawable resource to use as the small-icon. The name should not include the extension. | | `title` | `string` | | Required. The label to display for the action button. | | `callback` | `string` | | Required. The event to be emitted when the action button is pressed. | | `foreground` | `boolean` | `true` | Optional. Whether or not to bring the app to the foreground when the action button is pressed. | | `inline` | `boolean` | `false` | Optional. Whether or not to provide a quick reply text field to the user when the button is clicked. | | `replyLabel` | `string` | `Enter your reply here` | Optional. If you don't include a `replyLabel` in your action the default will be used. | ## Led in Notifications You can use a Led notifcation and choose the color of it. Just add a `ledColor` field in your notification in the ARGB format array: ```json { "registration_ids": ["my device id"], "data": { "title": "Green LED", "message": "This is my message with a Green LED", "ledColor": [0, 0, 255, 0] } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Green LED', message: 'This is my message with a Green LED', ledColor: [0, 0, 255, 0] } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` ## Vibration Pattern in Notifications You can set a Vibration Pattern for your notifications. Just add a `vibrationPattern` field in your notification: ```json { "registration_ids": ["my device id"], "data": { "title": "Vibration Pattern", "message": "Device should wait for 2 seconds, vibrate for 1 second then be silent for 500 ms then vibrate for 500 ms", "vibrationPattern": [2000, 1000, 500, 500] } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Vibration Pattern', message: 'Device should wait for 2 seconds, vibrate for 1 second then be silent for 500 ms then vibrate for 500 ms', vibrationPattern: [2000, 1000, 500, 500] } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` ## Priority in Notifications You can set a priority parameter for your notifications. This priority value determines where the push notification will be put in the notification shade. Low-priority notifications may be hidden from the user in certain situations, while the user might be interrupted for a higher-priority notification. Add a `priority` field in your notification. -2: minimum, -1: low, 0: default , 1: high, 2: maximum priority. ```json { "registration_ids": ["my device id"], "data": { "title": "This is a maximum priority Notification", "message": "This notification should appear in front of all others", "priority": 2 } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'This is a maximum priority Notification', message: 'This notification should appear in front of all others', priority: 2 } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` Do not confuse this with the FCM option of setting the [delivery priority of the message](https://developers.google.com/cloud-messaging/concept-options#setting-the-priority-of-a-message). Which is used by FCM to tell the device whether or not it should wake up to deal with the message. ## Picture Messages Perhaps you want to include a large picture in the notification that you are sending to your users. Luckily you can do that too by sending the following JSON from FCM. ```json { "registration_ids": ["my device id"], "data": { "title": "Big Picture", "message": "This is my big picture message", "style": "picture", "picture": "http://36.media.tumblr.com/c066cc2238103856c9ac506faa6f3bc2/tumblr_nmstmqtuo81tssmyno1_1280.jpg", "summaryText": "The internet is built on cat pictures" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Big Picture', message: 'This is my big picture message', picture: 'http://36.media.tumblr.com/c066cc2238103856c9ac506faa6f3bc2/tumblr_nmstmqtuo81tssmyno1_1280.jpg', summaryText: 'The internet is built on cat pictures' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` This will produce the following notification in your tray: ![2015-08-25 16 08 00](https://cloud.githubusercontent.com/assets/353180/9472260/3655fa7a-4b22-11e5-8d87-20528112de16.png) > Note: When the notification arrives you will see the title and message like normally. You will only see the picture when the notification is expanded. Once expanded, not only will you see the picture, but the message portion will disappear and you'll see the summary text portion. ## Background Notifications On Android if you want your `on('notification')` event handler to be called when your app is in the background it is relatively simple. First the JSON you send from FCM will need to include `"content-available": "1"`. This will tell the push plugin to call your `on('notification')` event handler no matter what other data is in the push notification. ```json { "registration_ids": ["my device id"], "data": { "title": "Test Push", "message": "Push number 1", "info": "super secret info", "content-available": "1" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Test Push', message: 'Push number 1', info: 'super secret info', 'content-available': '1' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` or if you want the payload to be delivered directly to your app without anything showing up in the notification center, just omit the tite/message from the payload like so: ```json { "registration_ids": ["my device id"], "data": { "info": "super secret info", "content-available": "1" } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { info: 'super secret info', 'content-available': '1' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` If you do not want this type of behaviour, just omit `"content-available": 1` from your push data and your `on('notification')` event handler will not be called. ### Use of content_available: true The FCM docs will tell you to send a data payload of: ```json { "registration_ids": ["my device id"], "content_available": true, "data": { "title": "Test Push", "message": "Push number 1", "info": "super secret info" } } ``` Where the `content_available` property is part of the main payload object. Setting the property in this part of the payload will result in the PushPlugin not getting the data correctly. Setting `content_available: true` will cause the Android OS to handle the push payload for you and not pass the data to the PushPlugin. Instead move `content_available: true` into the `data` object of the payload. The property name changes slightly to use a `-` instead of an `_`. So, `content_available` becomes `content-available` and `true` becomes `1` as per the example below: ```json { "registration_ids": ["my device id"], "data": { "title": "Test Push", "message": "Push number 1", "info": "super secret info", "content-available": "1" } } ``` ### Chinese Android Phones > Huawei, Oppo and Xiaomi These phones have a particular quirk that when the app is force closed that you will no longer be able to receive notifications until the app is restarted. In order for you to receive background notifications: - On your Huawei device go to Settings > Protected apps > check "My App" where. - On your Xiaomi make sure your phone has the "Auto-start" property enabled for your app. - On your Asus make sure your phone has the "Auto-start" property enabled for your app. More explicit instructions can be read on [Forbes website](https://www.forbes.com/sites/bensin/2017/07/28/how-to-fix-push-notifications-on-oppo-phones/#72a523371735). ### Application force closed In order to take advantage of this feature, you will need to be using cordova-android 6.0.0 or higher. In order to check if the change has been properly applied look at `platforms/android/**/MainActivity.java`. You should see an `onCreate` method that looks like this: ```java @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // enable Cordova apps to be started in the background Bundle extras = getIntent().getExtras(); if (extras != null && extras.getBoolean("cdvStartInBackground", false)) { moveTaskToBack(true); } // Set by <content src="index.html" /> in config.xml loadUrl(launchUrl); } ``` If you don't see the `if` statement that checks for the appearance of `cdvStartInBackground` you will probably need to do: ``` phonegap platform rm android phonegap platform add android phonegap build android ``` This should add the correct code to the `MainActivity` class. If you add `force-start: 1` to the data payload the application will be restarted in background even if it was force closed. ```json { "registration_ids": ["my device id"], "data": { "title": "Force Start", "message": "This notification should restart the app", "force-start": 1 } } ``` Here is an example using fcm-node that sends the above JSON: ```javascript const FCM = require('fcm-node'); // Replace these with your own values. const apiKey = 'replace with API key'; const deviceID = 'my device id'; const fcm = new FCM(apiKey); const message = { to: deviceID, data: { title: 'Force Start', message: 'This notification should restart the app', 'force-start': '1' } }; fcm.send(message, (err, response) => { if (err) { console.log(err); console.log('Something has gone wrong!'); } else { console.log('Successfully sent with response: ', response); } }); ``` ### Caching By default, when a notification arrives and 'content-available' is set to '1', the plugin will try to deliver the data payload even if the app is not running. In that case, the payload is cached and may be delivered when the app is started again. To disable this behavior, you can set a `no-cache` flag in the notification payload. 0: caching enabled (default), 1: caching disabled. ```json { "registration_ids": ["my device id"], "data": { "title": "Push without cache", "message": "When the app is closed, this notification will not be cached", "content-available": "1", "no-cache": "1" } } ``` ## Visibility of N