2

After getting the comment, i have deployed this folowing code to my firebase project and it was successfully deploed!.But there is no notifications been send to me. Please check my Firebase Realtime database Screenshot here for better understanding.

[ITS SOLVED NOW:IT WILL SEND NOTIFICATIONS TO ONLY ONE ID ie My Admin Device]

WORKING CODE:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firbase);
exports.codeformypeople = functions.database.ref('items/{id}').onWrite(evt => {

const payload = {
notification: { title: 'New Customer Requested', body: 'Touch to Open The App', badge: '1', sound: 'default', }
};
const token ="Lsn-bHfBWC6igTfWQ1-h7GoFMxaDWayKIpWCrzC";//replace with ur token

if (token) {
console.log('Toke is availabel .');
return admin.messaging().sendToDevice(token, payload);
} else {
console.log('token error');
}
});

[Mydatabase Structure[1]

SEE THIS VIDEO LINK FOR MORE DETAILS

note:If your app is opened and minmized then it will show notification,but if the app is opened and you are using,or if the app is terminated force close then it will not work!!

Rajesh
  • 3,562
  • 7
  • 24
  • 43

1 Answers1

5

You can use firebase cloud function to trigger notification. Here is snippet of cloud functions which i am using to trigger notification:

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.pushNotification = functions.database.ref('/Notifications/{pushId}')
 .onWrite(( change,context) => {
    console.log("Push Notification event triggered");
    var request = change.after.val();
    var payload = {
        data:{
            username: request.userName,
        }
    };
    admin.messaging().sendToDevice(request.userTokenId, payload)
    .then(function(response){
        console.log("Successfully sent message: ",response);
        console.log(response.results[0].error);
    })
    .catch(function(error){
        console.log("Error sending message: ", error)
    })
 })

Below i have provided my notification structure, you can see below.This function will trigger if any new data is being pushed in database notification node. To see what is output/error you are getting when this function is trigger go to firebase admin panel > Functions > Logs.

enter image description here

You have deployed function code perfectly, but you forgot to add refresh tokenId in your database as you can see in above picture i am saving userTokenId in my database and in function admin.messaging().sendToDevice(request.userTokenId, payload) i am using that tokenId, this tokenId is used to send notification to particular device, you can get this tokenId using FirebaseInstanceId.getInstance().getToken() and save this in your fbproject1 > items database sturcture. please refer this & this

Rohit Maurya
  • 730
  • 1
  • 9
  • 22
  • I hope you have given the code which can be used in Native Android,but for me it seems very much different looking than Flutter code..If you don't mind is it the code for flutter?? – Rajesh Jun 03 '18 at 09:18
  • 1
    @RajeshJr. This code is not android native code ,this code is of firebase cloud function which you have to write down in firebase function in firebase console, when you will add any data in notification database node from your flutter code, this function will trigger and notification will be sent – Rohit Maurya Jun 03 '18 at 11:52
  • ,Its my1st time i ive opened the fucntions console in firebase then downloaded nodejs and npm and initiated firebase,edited the index.js in vscode Pasted your above code (as it is ) then deplyed the code succesfully,Firebase also showing this deployed function in my browser,But when i change the values in realtime database no pushnotification is being received,but in manually sending cloud message notification is working.this automatic code is not sending any notifications?!!???! – Rajesh Jun 05 '18 at 04:56
  • 1
    @RajeshJr. Please check the answer i have updated and let me know if you need any help. – Rohit Maurya Jun 05 '18 at 05:39
  • ,pls see my updated question with screenshot of my Database,Am i did the thing right??[I don't want to send notifications to all the people who use my app,but i want to send notifications to only one app] – Rajesh Jun 05 '18 at 16:35
  • 1
    @RajeshJr. Please check the answer i have updated and let me know if you need any help. – Rohit Maurya Jun 05 '18 at 17:18
  • 1
    `admin.messaging().sendToDevice(request.body, payload)` in this your first parameter should be tokenId and second will be your payload. – Rohit Maurya Jun 05 '18 at 17:20
  • I'm so sorry to say this I'm not using any token Ids are User names,My topic contains simple Fields,Just "body" "message" "title"..I'm having completly no idea on this codes,...The screen shot is my exact database,Then how my should be like?? – Rajesh Jun 07 '18 at 12:13
  • 1
    if you want to send notification to only single person than there is no way, you will have to use tokenId, but if you want to send notification based on topic than you can just change `admin.messaging().sendToDevice(request.userTokenId, payload)` to `admin.messaging().sendToTopic(topicname,payload)` . Hope this will help you. – Rohit Maurya Jun 07 '18 at 14:22
  • is it helped me a lot because i need to target that specifc App by giving this "sendToTopic".....In 2nd line of ur code exports.pushNotification =functions.database.ref('/Notifications/{pushId}') what should i type in the place of {pushId}..Am i want to replace that with anything or i must leave {pushId} as like this?? – Rajesh Jun 07 '18 at 15:56
  • 1
    if you have same database structure as you have provided in your question than you have to write like this `ports.pushNotification =functions.database.ref('/fbproject1/item/{pushId}')` here `{pushId}` is your firebase auto generated key. – Rohit Maurya Jun 07 '18 at 16:35
  • successfully completed bro,I have request aguy in youtube he made a video for me and he helped me via teamviewer no its fixed!!Thanks for responding to all of my silly questions – Rajesh Jun 08 '18 at 07:32