且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在每次用户注册到我的应用程序时使用Cloud Functions for Firebase发送通知

更新时间:2023-09-08 13:15:16

用户'表,您存储用户信息,当一个新用户注册,并将他的信息存储在firebase数据库。



查看我附加的截图数据库。我发现用下面的代码新增了userId和notificationToken:
$ b

  exports.sendNotification = functions.database.ref(用户/ {userId} / {notificationToken})
.onWrite(event => {
const userId = event.params.userId;
const notificationToken = event.params.notificationToken;

var payload = {
data:{
title:Welcome to ChitChat Group,
message:You may have new messages
}
$;
admin.messaging()。sendToDevice(notificationToken,payload)
.then(function(response){
console.log(Successfully sent message:,response) ;
。)
.catch(function(error){
console.log(Error sending message:,error);
})
}



如果您需要其他用户的详细信息, userId。


I have created a mobile application I need to give notification when ever user get registered. if I delete the "Notifications" database reference in every time when I want to create a user it will give Notification otherwise it not.

//here is my android studio java code when user registered

 if (task.isSuccessful()){
  DatabaseReference reference =FirebaseDatabase.getInstance().getReference("Notifications");
  reference.child("token").setValue(FirebaseInstanceId.getInstance().getToken());
 }

//this the class I extends Firebase Messaging

public class MessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if(remoteMessage.getData().size()>0){
            Map<String,String> payload = remoteMessage.getData();

            showNotification(payload);
        }
    }

    private void showNotification(Map<String, String> payload) {
        NotificationCompat.Builder builder= new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle(payload.get("title"));
        builder.setContentText(payload.get("message"));
        builder.setAutoCancel(true);

        Intent intent = new Intent(this,MainTabActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

        stackBuilder.addNextIntent(intent);
        PendingIntent pendingIntent=stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);

        NotificationManager n = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

        n.notify(0,builder.build());
    }
}

//this the class I set token

public class InstanceIdService extends com.google.firebase.iid.FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        String refreshToken = FirebaseInstanceId.getInstance().getToken();

        DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Notifications");
        reference.child("token").setValue(refreshToken);
    }
}

//this is my index.js file

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

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

exports.sendNotification = functions.database.ref("Notifications")
    .onWrite(event => {
        var request = event.data.val();
        var payload = {
            data: {
                title: "Welcome to ChitChat Group",
                message: "You may have new messages"
            }
        };

        admin.messaging().sendToDevice(request.token, payload)
            .then(function (response) {
                console.log("Successfully sent message: ", response);
            })
            .catch(function (error) {
                console.log("Error sending message: ", error);
            })    
    });

Instead of working on 'Notification' you should use 'User' table, where you store user information, when a new user registered and you stored his info on firebase database.

Have a look at attached screenshot of my database. I found newly added userId and notificationToken with below code:

exports.sendNotification = functions.database.ref("Users/{userId}/{notificationToken}")
    .onWrite(event => {
      const userId = event.params.userId;
      const notificationToken = event.params.notificationToken;

      var payload = {
        data: {
            title: "Welcome to ChitChat Group",
            message: "You may have new messages"
        }
    };
      admin.messaging().sendToDevice(notificationToken, payload)
        .then(function (response) {
            console.log("Successfully sent message: ", response);
        })
        .catch(function (error) {
            console.log("Error sending message: ", error);
        }) 
}

If you need any other user detail, you can fetch that as well with the help of userId.