Huawei Push Kit, payload sent does trigger onMessageReceive - android

Based on the documentation I follow here documentation
the payload I had sent does not trigger onMessageReceived method for me to parse it instead it automatically trigger notification by the Huawei notification center.
this is a sample payload I've sent, and I've already include foreground_show and set it to false as mention in the web:
{
"validate_only":false,
"message": {
"notification": {
"title": "message title",
"body": "message body"
},
"android": {
"notification": {
"foreground_show": false,
"click_action": {
"type": 3
}
}
},
"data":"{'param2':'value1','param3':'value2'}",
"token": [
"ABW18Q4Rw5CAB68f9yS_1f859k0s-t3G1aIZheq5l6TedFj_Iold4I6M2EK-pwPTzt6HXxL_"
]
}
}
the result was, it does not trigger onMessageReceive function but it automatically creates the notification on the device.
but if I remove notification and android from the payload and only sending data it successfully trigger onMessageReceive :
{
"validate_only": false,
"message": {
"data": "{'param1':'value1','param2':'value2'}",
"token": [
"ABW18Q4Rw5CAB68f9yS_1f859k0s-t3G1aIZheq5l6TedFj_Iold4I6M2EK-pwPTzt6HXxL_"
]
}
}
this is the class where I already override the onMessageReceived:
class CustomPushService : HmsMessageService() {
private val TAG = "PushTokenLog"
override fun onNewToken(token: String?, bundle: Bundle?) {
super.onNewToken(token, bundle)
Log.d(TAG, "receive token:$token")
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
Log.d(TAG, "onMessageReceived")
Log.d(TAG, "onMessageReceived:title:${remoteMessage?.notification?.title}")
super.onMessageReceived(remoteMessage)
}
}
I already include foreground_show: false and it wont trigger onMessageReceived unless if I only sending data in the payload then it will trigger onMessageReceived.
so is it not possible to send full payload as shown in the first payload and trigger onMessageReceived so that I can process the payload? and please let me know if my method wrong

In your request payload, you've set "message.android.notification.foreground_show” to “false”, which means your app is in the foreground and you will get the message data in the function onMessageReceived. Please double-check if your app is in the foreground.
Your device EMUI must be greater than EMUI 9.1.0, and Push SDK version must be greater than 4.0.
The class CustomPushService definition is good.
I used your 1st sample payload to test on my project. It worked very well. Please see below screenshot. The process entered into the function onMessageReceived as below.
Please refer to https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-server-dev-0000001050040110 and https://developer.huawei.com/consumer/en/doc/development/HMSCore-References/https-send-api-0000001050986197 for more information.
If you still have issues, please share logcat logs with me.

Related

How to send simple "push notification" from one device to other device?

I have an application that I made with Flutter. I am trying to write a method for users to add each other as friends in my application, but before I do this, I want to send push notifications from one device to the other. Actually, I think if I start, I can solve the rest with my own algorithm.
Ways I've tried:
installed node.js
from project terminal: firebase login
firebase init
functions file created and exists in my project
i have index.ts file
I get unique token for each device when app opened.
I want to put a simple notification sending code in the index.ts file, but I couldn't. And this notification should work from one device to another.
Here is simple solution to send device to device notification.
First create json formatted parameters like below
var params = {
"to": "device token",
"notification": {
"title": "Notification Title",
"body": "Notification Message",
"sound": "default",
},
"data": {
"customId": "01",
"badge": 0,
"alert": "Alert"
}
};
Then var url = 'https://fcm.googleapis.com/fcm/send'; call as api.
Get response like below code
var response = await http.post(url,
headers: {
"Authorization": "key= Web server Key over here",
"Content-Type": "application/json"
},body: json.encode(params)
);
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
print("fcm.google: "+map.toString());
}
else {
Map<String, dynamic> error = jsonDecode(response.body);
print("fcm.google: "+error.toString());
}

Notification not receive when Application terminated in android

I use firebase push notification to device token. When app is opening or in foreground I can get notification well. But when app is kill or clear app on current task, I cannot receive notification send.
I have tried on onMessageReceived aleardy at first time work. but now it's not work when killed app.
Code Receive Notification:
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(p0: RemoteMessage) {
val data = p0!!.data
Log.e("AAAAAAAAAAAAA: ","data
111111111111111111111111111111111111111111111111:" + data["key1"])
}
}
Post Send notification data:
Send to: https://fcm.googleapis.com/fcm/send
Data :
{
"to" : "token key",
"data": {
"key1" : "value1",
"key2" : "value2",
"other_key" : true
}
}
Result, for app is opening, I can receive data well, but when killed I cannot receive data.
If you're sending data to
https://fcm.googleapis.com/fcm/send
you're using the legacy http protocol as you can see here
This is not very clear in documentation.
In this protocol to receive the data message when app is in background or closed you should use this payload:
{
"to" : "token key",
"data": {
"key1" : "value1",
"key2" : "value2",
"other_key" : true
},
"priority" : 10,
"time_to_live" : 60
}
Test first with maximum priority (10) and then downgrade according t your needs. Also adjust time_to_live in seconds according to your needs.

Invalid topic value provided - While sending FCM to a topic

I am trying to send an FCM message to a topic. But getting "Invalid topic value provided" error from the server.
Json Payload
{
"message":{
"topic":"/topics/news",
"data":{
"title":"Hellow World",
"message":"This is the Topic Message",
"type1":"100",
"type2":"abc"
}
}
}
Response
{
"error":{
"code":400,
"message":"Request contains an invalid argument.",
"status":"INVALID_ARGUMENT",
"details":[
{
"#type":"type.googleapis.com/google.rpc.BadRequest",
"fieldViolations":[
{
"field":"message.topic",
"description":"Invalid topic value provided."
}
]
},
{
"#type":"type.googleapis.com/google.firebase.fcm.v1.FcmError",
"errorCode":"INVALID_ARGUMENT"
}
]
}
}
I have tried topic value as "news" (without '/topics/') but it throws same error. I can send message to the topic from firebase console without any problem.
Any help appreciated. TIA
Edit1 - Notification payload below works fine but data payload doesn't work. As per documentation, data payloads too are allowed https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
Request
{
"message":{
"topic" : "foo-bar",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message",
}
}
}
EDIT2 :
This works. I had a small bug in my code which was adding additional quotes to the topic. Below request works like a charm
{
"message":{
"topic":"news",
"data":{
"title":"Hellow World",
"message":"This is the Topic Message",
"type1":"100",
"type2":"abc"
}
}
}
according to doc yor request should be like this:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}

Push notification to Android from Rails api using FCM is not sending the notification?

i am coding an Api Rest in rails 5, using gem 'fcm' to send notifications. I have already configure firebase in my android app and I can send notifications successfully from the Firebase console, but from my rails api i cannot receive the notificacion in my device, this is my code:
this is my rails controller:
class AccionesController < ApplicationController
def enviar
require 'fcm'
fcm = FCM.new("AAAAlBfTsV4:AheregoesmySERVEKEYsXXm-vQGfMjVuo8TpYrApHsnGU4ZasdfajsdfñalUtf26LeND4U4lXFZZplpzJjTWoiisWP-Esl5afCSTmiDI9y5gP6OObqY76NVcOn9ceaIUGMZ")
# fcm = FCM.new("my_server_key", timeout: 3)
registration_ids= [params[:devicetoken]] # an array of one or more client registration tokens
options = {data: {score: "mynewscore"},
notification: {
title: "Message Title",
body: "Hi, Worked perfectly",
icon: "myicon"}
,collapse_key: "testeando desde rails", priority: "high"}
response = fcm.send(registration_ids, options)
render json: response
end
def noti_params
params.permit(:devicetoken)
end
end
I execute from Postman this is the route that execute the controller:
http://localhost:3000/acciones/enviar?here goes the device token as parameter
And, here is the response:
{"body":"{\"multicast_id\":5276983113254623155,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1502991819420287%2293308c2293308c\"}]}","headers":{"content-type":["application/json;
charset=UTF-8"],"date":["Thu, 17 Aug 2017 17:43:39
GMT"],"expires":["Thu, 17 Aug 2017 17:43:39
GMT"],"cache-control":["private,
max-age=0"],"x-content-type-options":["nosniff"],"x-frame-options":["SAMEORIGIN"],"x-xss-protection":["1;
mode=block"],"server":["GSE"],"alt-svc":["quic=\":443\"; ma=2592000;
v=\"39,38,37,35\""],"accept-ranges":["none"],"vary":["Accept-Encoding"],"connection":["close"]},"status_code":200,"response":"success","canonical_ids":[],"not_registered_ids":[]}
the response shows success: 1 and status code: 200 but the notification never reaches the device,and the firebase console does not show the message.
Am I missing something?
please help?
or is there another way or ruby gem to send notification with a clear example?
any suggestions are welcome... thanks in advance
Instead of using fcm gem, you can also use RestClient gem. The usage for fcm notifications is as follow.One thing to note is if the payload is passing using ".to_json", the header content type also must be specified as json. Hope this help.
def self.send_noti(device_token)
options = data().merge ({"to": "#{device_token}"})
RestClient.post("https://fcm.googleapis.com/fcm/send", options.to_json, headers={'Content-Type' => 'application/json','Authorization' => "key=#{ENV['fcm_token']}"})
end
def self.data()
options = {
"notification": {
"body": "Your noti body",
"title": "Your noti title"
},
"data": {
"d1": "Your data" #can be any, d1, status or whatever
}
}
end
rest-client gem
fcm_client = FCM.new(your_firebase_key)
registration_ids= [user_device_token]
options = {
priority: 'high',
data: {
message: "Hai",
location: location
},
notification: {
body: "Hai",
location: "location",
sound: 'default'
}
}
fcm_client.send(registration_ids, options)
end
end
try this message options because the error should be your notification syntax.
options = {
priority: 'high',
data: {
message: "Hai",
location: location
},
notification: {
body: "Hai",
location: "location",
sound: 'default'
}
}

FCM notification title remains "FCM Message"

I'm trying to use the Firebase Cloud Messaging. I send the notifications from a Node.js server to my apps that are registered to the notification system.
My problem is that on Android 5.1 the notification is "FCM Message" even if I setted the title attribute in the nofitification json. It works fine in Android 6.0. I tried to reboot my device as well.
And this is the code I use to send the notification:
function sendNotificationToUser(userToken, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
"title": 'My App Name',
"body": message,
"sound": 'default'
},
to : userToken
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
As you can see the notification title I send is "My App Name" but on device it shows "FCM Message".
What do I have to do?!
You need to pass the title and then receive it in remoteMessage.getNotification().getTitle() , this will catch title and then display in the top or pass complete JSON from web and receive like this
JSONObject jsonObject = new JSONObject(remoteMessage.getData());
Here is the complete method:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// ...
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: https://firebase.google.com/support/faq/#fcm-android-background
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
Ref link
I found that it is a problem related to onMessageReceived callback.
As you can see on the receive a FCM guide
This is expected. (Tested upto Android 10)
FCM has different behaviours for app status (foreground and background / killed).
You should handle this by the payload you sent from server, according to your use case.
The msg sent from server has to be sent in either "notification" or "data" format, from dashboard or server side api.
Note: From firebase dashobard you can only send "notification" body and not data. In such cases, FCM will directly display the notif without giving a callback to your app.
Server side
Below are sample formats :
Notification Type Format
Note : Android System will by default display the notification in the notification tray and you don't need to display it.
{
"to": "your_token_id",
"notification" : {
"title" : "FCM Notification title!",
"body" : "FCM Notification subtext!",
"content_available" : true,
"priority" : "high"
}
}
Data Format (For receiving callback in app, in foreground and background)
Note : You have to handle callback and display notif on your own.
{
"to": "your_token_id",
"data" : {
"title" : "FCM Notification Title ",
"subtext" : "FCM Notification Sub Title",
"type" : "999",
"priority" : "high"
}
}
Android Client
To handle the payload received in your Android receiver, checl the official guide here
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
remoteMessage.data.isNotEmpty().let {
Log.d(TAG, "Message data payload: " + remoteMessage.data)
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob()
} else {
// Handle message within 10 seconds
handleNow()
}
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
Check the documentation here
This is how i get the title from remote messages:
var title = ""
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.notification != null) {
title = remoteMessage.notification!!.title!!
}
}
val notificationBuilder = NotificationCompat.Builder(applicationContext, channelId)
.setContentTitle(title)

Categories

Resources