3

I'm using com.google.firebase:firebase-messaging:10.0.1 for Android and trying to make the device vibrate while application is in background and a push notification is received. I send following json to FCM server:

to: 'topics/...',
notification: {
    title: 'New Message',
    body: 'top security body',
    sound: 'mysound',
    action_click: 'top_security'
}

When the app is in foreground, the onMessageReceived method of FirebaseMessagingService is triggered and I can add vibration. But, when the app is in background, onMessageReceived is not called and I have no control on the vibration. My first thought was to use data block instead both for background and foreground, but iOS client does not receive pushes in background if there is no notification block.

So how can I add vibration to push notification when the app is in background? P.S. When I turn on vibrate mode on the device, the push notification cause vibrating instead of playing the sound.

morten.c
  • 3,414
  • 5
  • 40
  • 45
IliaEremin
  • 3,338
  • 3
  • 26
  • 35
  • because you should send silent notification , follow this [link](http://stackoverflow.com/questions/37570200/firebase-silent-apns-notification) – mahmoud moustafa Mar 02 '17 at 13:28
  • Please refer my answer in this link, http://stackoverflow.com/a/42505362/1404798 – Thirumalvalavan Mar 02 '17 at 13:35
  • @mahmoudmoustafa I'm using android, see tags – IliaEremin Mar 02 '17 at 13:47
  • See also this answer and [this answer](https://github.com/evollu/react-native-fcm/issues/27) and [this answer](https://stackoverflow.com/questions/38446300/firebase-cloud-messaging-notification-vibration) – Kato Sep 15 '17 at 17:07

1 Answers1

2

Use data payload instead of notification payload because data payload will trigger onMessageReceived even though the app is background or foreground. Your request will look like this

data: {
    title: 'New Message',
    body: 'top security body',
    sound: 'mysound',
    action_click: 'top_security'
}

To retrieve the data from data payload inside onMessageReceived, call remoteMessage.getData(); which will return the result in a Map<String,String>

For example:

Map<String, String> data = remoteMessage.getData();
String title = data.get("title");
String body = data.get("body");

Then customize the notification as you want with that data.

Hope this helps :)

Wilik
  • 7,630
  • 3
  • 29
  • 35
  • We use push notifications both for android and ios. iOS client does not show push notification in background if there is no `notification` block. – IliaEremin Mar 02 '17 at 13:46
  • You are also able to combine both of the payloads (notification and data) in one request. Have you tried it? @IlyaEremin – Wilik Mar 02 '17 at 14:12