簡體   English   中英

每當用戶注冊到我的應用程序時,如何使用Cloud Functions for Firebase發出通知

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

我已經創建了一個移動應用程序,當用戶注冊時,我需要發出通知。 如果我每次要創建用戶時都刪除“ Notifications”數據庫引用,它將給出Notification,否則不提供。

//這是用戶注冊時我的android studio java代碼

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

//這是我擴展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());
    }
}

//這是我設置令牌的類

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

代替處理“通知”,您應該使用“用戶”表,當新用戶注冊並將其信息存儲在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的幫助下進行獲取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM