How to send an array in dart post request - android

I try to send messages to device groups with their registration_ids.
This my code:
List<String> tokens=["token1","token2"];
final url='https://fcm.googleapis.com/fcm/send';
http.post(url,headers:{
"Accept": "application/json",
"Authorization":"key=mykey"
,"project_id":"proID"
},
body:
{
"registration_ids" :tokens ,
"collapse_key" : "type_a",
"notification" : {
"body" : "Body of Your Notification",
"title": "Title of Your Notification"
}
}
When the app runs this error displays:
Exception has occurred.
_CastError (type 'List' is not a subtype of type 'String' in type cast)
How to fix it?

Problem solved; I just encoded the body:
List<String> tokens=["token1","token2"];
final url='https://fcm.googleapis.com/fcm/send';
http.post(url,headers:{
"Accept": "application/json",
"Authorization":"key=mykey"
,"project_id":"proID"
},
body:json.encode(
{
"registration_ids" :tokens ,
"collapse_key" : "type_a",
"notification" : {
"body" : "Body of Your Notification",
"title": "Title of Your Notification"
}
)
}

you are having problems due to the registration is expecting a JSON string but you are passing list object to it. You can simply resolve that by casting your List<String> to String.
By casting the token list using toString() method you will get a String like this "['token1','token2']"
Here's the modified code:
List<String> tokens=["token1","token2"];
final url='https://fcm.googleapis.com/fcm/send';
http.post(url,headers:{
"Accept": "application/json",
"Authorization":"key=mykey"
,"project_id":"proID"
},
body:
{
"registration_ids" : tokens.toString() ,
"collapse_key" : "type_a",
"notification" : {
"body" : "Body of Your Notification",
"title": "Title of Your Notification"
}
}

Related

Firebase push notifications is not triggering onMessageReceive on Android when the app is closed

When I don't send the notification object in the JSON request to the Firebase API, the onMessageReceive is triggered normally and my notifications work as intended, but, when I use the notification or the android object in the JSON that I send as params the onMessageReceive is not triggered when the app is in background.
I've been trying to debug this but I can't figure it out.
I have a simple class in my server that user Firebase API to send the push notifications.
In the params that I send to the server, I'm sending the following attributes.
"apns": {
"title": title.nil? ? "Testing notification" : title,
"body": body.nil? ? "This is a test push notification, liking it?" : body,
"mutable_content": true,
"sound": sound.nil? ? "enabled" : sound
},
"android": {
"title": title.nil? ? "Testing notification" : title,
"body": body.nil? ? "This is a test push notification, liking it?" : body,
"sound": sound.nil? ? "enabled" : sound
},
or the following for cross plataforms.
"notification": {
"title": title.nil? ? "Testing notification" : title,
"body": body.nil? ? "This is a test push notification, liking it?" : body,
"mutable_content": true,
"sound": sound.nil? ? "enabled" : sound
},
This configuration is suggested by google in the following official documentation
Firebase Documentation
The only way it actually works is when I DO NOT SEND the notification or android object and generate the notification with the data I send in the data attribute of the JSON object sended to the Firebase API
params = {
"#{key}": to,
# "apns": {
# "title": title.nil? ? "Testing notification" : title,
# "body": body.nil? ? "This is a test push notification, liking it?" : body,
# "mutable_content": true,
# "sound": sound.nil? ? "enabled" : sound
# },
# "android": {
# "title": title.nil? ? "Testing notification" : title,
# "body": body.nil? ? "This is a test push notification, liking it?" : body,
# "sound": sound.nil? ? "enabled" : sound
# },
"data": {
"title": title,
"body": body
}
}.to_json
The notifications sent through the Firebase console don't work either.
¿Any ideas?
Use Below Xml Code in andorid manifest
<service
android:name=".services.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Create MyFirebaseMessaginfService Class to recive Firebase Notification When App is close.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
LocalBroadcastManager broadcaster;
#Override
public void onCreate() {
broadcaster = LocalBroadcastManager.getInstance(this);
}
#Override
public void onNewToken(#NonNull String token) {
Log.d(TAG, "Refreshed token: " + token);
Const.FireBaseTokenID=token;
Log.e(TAG, "onComplete:Service "+Const.FireBaseTokenID );
}
public MyFirebaseMessagingService() {
getFireBaseID();
}
public static void getFireBaseID() {
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if(!task.isSuccessful()){
Log.w(TAG, "getInstance ID Failed "+task.getException() );
return;
}
String token = task.getResult().getToken();
Log.e(TAG, "onComplete:Service Method "+token );
}
});
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String call_api=remoteMessage.getData().get("callapi");
String play_id=remoteMessage.getData().get("play_id");
String clue_number=remoteMessage.getData().get("clue_number");
String title=remoteMessage.getData().toString();
Log.e(TAG, "onMessageReceived: callapi "+call_api );
Log.e(TAG, "onMessageReceived: play_id "+play_id );
Log.e(TAG, "onMessageReceived: clue number "+clue_number );
Log.e(TAG, "onMessageReceived: title "+title );
Intent intent= new Intent("remoteMessage");
intent.putExtra("call_api", call_api);
intent.putExtra("play_id", play_id);
intent.putExtra("clue_number", clue_number);
intent.putExtra("title", title);
broadcaster.sendBroadcast(intent);
}
}
You should send with format data, same:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}

How to show the FCM on the react native app while it is on foreground

I want to show the notification when app is in foreground and it receives the FCM just WhatsApp and other application shows. On the background I am receiving the notification on the notification bar but nothing happen when it receives while user is using the app. I am looking something like default android small popup from top. I am using the following body to send the FCM.
{
"to": "/topics/chatProperty_P00025_14",
"notification" : {
"body" : "great match!",
"content_available" : true,
"priority" : "high",
"title" : "Portugal vs. Denmark",
"sound":"default",
"vibrate":true
},
"data" : {
"body" : "14_P00025",
"content_available" : true,
"priority" : "high",
"title" : "Portugal vs. Denmark",
"type" : "propertyChat",
"sound":"default",
"vibrate":true
}
}
See the following sample code:
let message = {
to: "fcm_device_token",
data: {
custom_notification: {
body: "Your message",
custom_data: "Any custom data you want to send",
sound: 'default',
priority: "high",
show_in_foreground: true
}
}
}

Firebase push notification not showing on phone despite successful response

I am sending a push token to a specific device via the FCM API on testing with Postman, but I intend to send them from the server.
{
"to" : "my_device_token",
"notification" : {
"notificationTitle" :"test from server",
"notificationBody" :"test lorem ipsum"
}
}
I am receiving the response
{
"multicast_id": 4996861050764876123,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results":
[
{
"message_id": "0:1519567530487886%f95ee7d4f95ee123"
}
]
}
Which shows no error, however I don't get any notifications on my phone.
I tried the same device token using on firebase website "Notifications => New Message => Single Device", and it works.
I see threads about not receiving the notifications when the app is not running, however I don't get any even if the app is running.
Edit: My application is built using Xamarin.Android, if relevant.
The notification property keys are title and body:
{
"to" : "my_device_token",
"notification" : {
"title" :"test from server",
"body" :"test lorem ipsum"
}
}
See Table 2b in the documentation.
I am sending push in a single devices using via FCM api. The JSON is given below.
In the case of Android
{
"to" : "device Tokens", // Your android device token
"data" :
{
"body" : "test",
"title" : "test",
"pushtype" : "events",
};
In the case of IOS json
{
"to" : "device Tokens", // iphone tokens
"data" :
{
"body" : "test",
"title" : "test",
"pushtype" :"events",
},
"notification" : {
"body" : "test",
"content_available" : true,
"priority" "high",
"title" = "C#"
}
} ;
put in index.js
PushNotification.configure({
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
},
requestPermissions: Platform.OS === 'ios'
})
in your screen
createChannels =()=>{
PushNotification.createChannel(
{
channelId:"test-channel",
channelName:"Test-channel"
}
)
}
handleNotification=()=>{
PushNotification.localNotification({
channelId:"test-channel",
title:"Kinza ",
message: "hi gow adww biy",
});
PushNotification.localNotificationSchedule({
channelId: "test-channel",
title:"Alram",
message:"Hi how are you",
date: new Date(Date.now() + 20*1000),
allowWhileIdle:'true',
});
}

How to extract encapsulated JSON from Firebase Cloud Message?

I send from Firebase Messages in this structure:
{
"to": "/topics/myapp",
"data": {
"id" : "id123",
"title" : "lksdjkrfrfrereflsjd",
"body" : "fsdfsd",
"de": {
"key1" : "val1",
"key2" : "val2"
},
"en": {
"key3" : "val3",
"key4" : "val4"
}
}
}
in my override fun onMessageReceived(remoteMessage: RemoteMessage?) method my remoteMessage object has a data field which is from type: Map<String, String>
How can I access de and en from remoteMessage ?
EDIT: It is developed for Android

Firebase data payload messages remove special characters from string for some reason

{
"to" : "required token..",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
"icon" : "myicon"
},
"data": {
"id": 1,
"action": "load_content",
"frequency": 1,
"payload": "{\"module\":\"news\",\"id\":32}"
}
}
Code:
payload = data.get("payload");
Log.i(TAG, " received payload =" + payload);
When I extract the payload that I'm sending as a string and put it out on the logcat I get
{"module":"news","id":32}
I would want to keep the string as it is sent (with the '/' in it). I'm not really sure why that's happening. Any help would be highly appreciated.
Currently you are only escaping the double quote with \" if you want to retain the backslash you will also have to escape that with \. So your resulting field would look like:
"payload": "{\\\"module\\\":\\\"news\\\",\\\"id\\\":32}"
That should result in output that looks like:
{\"module\":\"news\",\"id\":32}

Categories

Resources