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

How do i give notification every time user get registered to my app, using Cloud Functions for Firebase

我创建了一个移动应用程序,我需要在用户注册时发出通知。如果我每次想创建用户时都删除 "Notifications" 数据库引用,它会发出通知,否则不会。

//这是我的android工作室java用户注册时的代码

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

//这是 class 我扩展了 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());
    }
}

//这个class我设置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);
    }
}

//这是我的index.js文件

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);
            })    
    });

您应该使用 'User' table,而不是在 'Notification' 上工作,当新用户注册并且您将他的信息存储在 firebase 数据库中时,您在其中存储用户信息。

查看我的数据库的附加屏幕截图。我发现新添加的 userId 和 notificationToken 代码如下:

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 My 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 的帮助下获取。