Can we generate push notification using onPressed in Flutter (using Firebase)? - android

I know that we can use firebase cloud messaging and from the firebase console only we can generate notifications for flutter app (after we setup up everything in the app
). But is there any way by which I can generate notification on press of a button. For e.g. The admin of the app adds a new event, as soon as he/she presses [Add Event] button, a notification gets generated for each user (using firebase) that a new event has been added? How can this be achieved?

You can call your server in onPressed: (https://docs.flutter.dev/cookbook/networking/fetch-data)
Example:
onPressed: () async {
await http.get(Uri.parse("https://your-server.com/add-event"));
}
then from your server you can send a fcm notfication to the devices: (https://firebase.google.com/docs/cloud-messaging/server#implementing-the-xmpp-connection-server-protocol)
Example:
const registrationTokens = [
'YOUR_REGISTRATION_TOKENS',
];
const message = {
data: {new_event: 1},
tokens: registrationTokens,
};
getMessaging().sendMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});

Related

FCM wont stack similar messages?

I am trying to stack similar messages instead of sending separate notification for every same message.
Below is my code
const payload = {
notification: {
title: `added new report`,
body: change.after.data().report_title,
tag: "ReportLog",
},
data: {
click_action: "FLUTTER_NOTIFICATION_CLICK",
sound: "default",
status: "done",
},
};
const options = {
priority: "high",
collapseKey: "ReportLog",
};
await admin.messaging().sendToDevice(tokens, payload, options);
SO suppose i send the same message again and again , instead of stacking the messages, the old notification get replace by new
On the server side you can "remember" the last notify and don't send another. (Bad idea)
On the client you can do the same. (Also bad idea)
But the thing is, that the "remember" logic won't work if the app is the background, because the notify will be handled by the system and not by your logic in the app.

Send push notifications via AWS Pinpoint to specified User

I am using react-native and amplify to send push notifications to devices via AWS Pinpoint. I can get the generated token for the devices. But I just need to send push notifications using user Id. I try to update the endpoint, but it's not working. Can anyone suggest me the proper way to handle this?
PushNotification.onRegister((token) => {
console.log('in app registration', token);
Analytics.updateEndpoint({
address: token,
channelType: "GCM",
OptOut: 'NONE',
userId: "12345"
}).then(data => {
console.log(data)
}).catch(error => {
console.log(error)
});
});
It depends how you would like to send the push notification. We have created UI that allows sending a push, which triggers a lambda.
Firstly, you need the app to update the endpoint with the token / address as you have done.
Then you can send the push from the lambda, as shown in this code.
const sendPushNotification = async () => {
const params = {
ApplicationId: "PINPOINT_ANALYTICS_ID",
SendUsersMessageRequest: {
Users: {
"12345": {} // replace numbers with userid here connected with pinpoint endpoint
},
MessageConfiguration: {
APNSMessage: {
Action: 'OPEN_APP',
Title: 'Title of push notification',
SilentPush: false,
Sound: 'default',
Body: 'Message you would like to send'
},
GCMMessage: {
Action: 'OPEN_APP',
Title: 'Title of push notification',
SilentPush: false,
Sound: 'default',
Body: 'Message you would like to send'
},
},
},
};
return pinpoint.sendUsersMessages(params).promise();
};
await sendPushNotification();
I was able to do that using #aws-amplify/analytics library. Following is the method that I used.
Analytics.configure(aws_exports);
PushNotification.onRegister((token) => {
//alert(token)
console.log('in app registration', token);
Analytics.updateEndpoint({
address: token, // The unique identifier for the recipient. For example, an address could be a device token, email address, or mobile phone number.
attributes: {
// Custom attributes that your app reports to Amazon Pinpoint. You can use these attributes as selection criteria when you create a segment.
hobbies: ['piano', 'hiking'],
interests: ['basketball']
},
channelType: 'GCM', // The channel type. Valid values: APNS, GCM
userId: '221XWsdfER234',
// User attributes
optOut: 'ALL',
userAttributes: {
interests: ['football', 'basketball', 'AWS']
// ...
}
}).then((data) => {
console.log(data)
}).catch(error => {
console.log(error)
})
});
With Amazon Pinpoint, you can’t send transactional message as Push notification. Meaning, you can’t send direct Push notification to a specific recipient.
Amazon Pinpoint - Push notification supports sending notifications to a targeted audience by creating a campaign and segment.
If it’s for testing only, from Pinpoint dashboard, you can send Test message to a specific user by using User ID or by using device token.
Read more here =>
Sending Transactional Messages from Your Apps - Amazon Pinpoint

cordova fcm push notifications using firebase functions issue

I am using firebase function and sending the notification like below
let pushPayload = {
notification: {
title: 'Doodles Notification',
body: "push testing",
sound: 'default',
badge: '1'
}
};
//push tokens need to be of customer as well as all the admins in the system. fetch admin push tokens
admin.messaging().sendToDevice(pushToken, pushPayload).then(
(resp) => {
console.log("push notification sent using test method")
return
}
).catch(
(err) => {
console.log("Error sending push notification:" + JSON.stringify(err))
return
}
)
The client side ionic app has method like below:
this.fcm.onNotification().subscribe(data => {
console.log("push message is:" + JSON.stringify(data))
alert(data.aps.alert.body)
});
on ios this all works great. however on android, the console.log prints
{"wasTapped":false}
I am ok with the above expected property but where is the data? The firebase documentation is confusing around it and I am sort of lost what is the correct payload I need to use that works with both ios and android.
Your pushPayload also needs to have a data array to pass data. I believe you also need speech marks around your keys:
"notification":{
"title":"Doodles Notification",
"body":"push testing",
"sound":"default",
"badge":"1"
},
"data":{
"Key1":"Test",
"Key2":"More data"
}
Documentation

Background Firebase Push Notifications in Cordova

I am using a phonegap-plugin-push for receiving notifications in Cordova Application. I am deploying on android Marsh-mellow for testing.
I want to see and store the contents of the Notifications received through Firebase Console when the app is in background.
Here is my Code -
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
var push = PushNotification.init({ "android": {"senderID": "91254247XXXX"}});
push.on('registration', function(data) {
console.log(data.registrationId);
//document.getElementById("gcm_id").innerHTML = data.registrationId;
});
push.on('notification', function(data) {
alert("On Notification function!!");
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
console.log("notification event");
console.log(JSON.stringify(data));
alert(JSON.stringify(data));
//Do something
});
push.on('error', function(e) {
alert(e);
});
}
When the app is in foreground (on screen) I receive the contents (title, message, data, etc.) properly and I am able to see them in alert box directly in the app.
But when app is in background (not on screen but running in backround), I get the notification in Notification Area. When I click on the notification received, it is redirecting me to the last opened page in the app.
The function push.on('notification', function(data) {} is not called. No alert messages are shown. Can someone help me how to access the notification message and data?
I found the answer after 2 days of research. We have to set "content-available" to 1 in the data field. Else it wont call on notification block if app is in background.
And this is not possible as of now through Google Firebase Console.
We have to send our custom payload messages (data or notification or both) seperately using any one of the firebase servers.
Detailed info can be found on the plugin's GitHub Page on background notifications.
I used NodeJs firebase-admin. I followed these setup guidelines and these steps for sending messages and it worked for me.
Here is my working code (NodeJS) -
var admin = require("firebase-admin");
var serviceAccount = require("pushnotificationapp-xxxxx.json"); //this is the service account details generated from server
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://pushnotificationappxxxxx.firebaseio.com/" //your database URL here.
});
var registrationToken = "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX....."; //registration token of the device
var payload ={
"data": {
"title": 'Test Push',
"message": 'Push number 1',
"info": 'super secret info',
"content-available": '1' //FOR CALLING ON NOTIFACATION FUNCTION EVEN IF THE APP IS IN BACKGROUND
}
};
//send the notification or message
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
UPDATE :
I implemented the same using php server too.
Here is my working php code for sending notifications using HTTP POST to FCM server-
<?php
$url = 'https://fcm.googleapis.com/fcm/send';
$data =
array(
"to" => "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX.....",
"data" => array(
"title"=> 'Test Push',
"message"=> 'Push number 1',
"info"=> 'super secret info',
"content-available"=> '1')
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => array("Content-Type:application/json",
"Authorization:key=AAAA1HfFM64:APA91XXXX...."), //this is the server authorization key from project settings tab in your Firebase Project
'method' => 'POST',
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo "Caught an error"; }
else{
echo $result;
}
?>
i was going through the same issue but i added "content-available": '1' also but my phone was not receiving any background push.
Finally i found that it was issue with my phone as mentioned here: https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#huawei-and-xiaomi-phones
Huawei and Xiaomi Phones
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.
Hope it will help someone.

Cloud Functions for Firebase: Sending topic notification to Android device not working

I was following this tutorial from Udacity where Cloud Functions for Firebase was used to change the data of a ref on data added.
I wanted to use similar function, but for sending a push notification to users subscribed to topic.
This is the function I am using.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/messages/{pushId}/text').onWrite((event) => {
const data = event.data;
console.log('Message received');
if(!data.changed()){
console.log('Nothing changed');
return;
}else{
console.log(data.val());
}
const payLoad = {
notification:{
title: 'Message received',
body: 'You received a new message',
sound: "default"
}
};
const options = {
priority: "high",
timeToLive: 60*60*2
};
return admin.messaging().sendToTopic("Message_Notifications", payLoad, options);
});
Looking at the Firebase function log I can see that the function gets called when I add a new value to the database. The I am subscribing to the topic in the mainactivity with
FirebaseMessaging.getInstance().subscribeToTopic("Message_Notification");
And after a few hours now I can see the topic in my topics list in firebase notification console. I send a notification from there and it worked.
What are the other things I need to do to have a notification show up every time a new message is added?
Any suggestion is appreciated. I am fairly new to Firebase. So if there is a better blog/post about it please redirect me so that I can learn more.
Thanks in advance.
In your Android app, you are subscribing to "Message_Notification" topic.
In your script, you're sending to "Message_Notifications" topic.
Either add an s in your Android app for the name of the topic or remove the excess s from your script.

Categories

Resources