首页 > 解决方案 > 从 Android 应用调用 sendFollowerNotification Firebase 函数

问题描述

所以我意识到,从 12.0 版开始,您可以直接从 Android 应用程序调用 Firebase 函数......这对于给定的发送消息示例是有意义的:

private Task<String> addMessage(String text) {
        // Create the arguments to the callable function.
        Map<String, Object> data = new HashMap<>();
        data.put("text", text);
        data.put("push", true);

        return mFunctions
                .getHttpsCallable("addMessage")
                .call(data)
                .continueWith(new Continuation<HttpsCallableResult, String>() {
                    @Override
                    public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                        // This continuation runs on either success or failure, but if the task
                        // has failed then getResult() will throw an Exception which will be
                        // propagated down.
                        String result = (String) task.getResult().getData();
                        return result;
                    }
                });
    }

...您将文本发送到函数的位置。

exports.addMessage = functions.https.onCall((data, context) => {
  // [START_EXCLUDE]
  // [START readMessageData]
  // Message text passed from the client.
  const text = data.text;
  // [END readMessageData]
  // [START messageHttpsErrors]
  // Checking attribute.
  if (!(typeof text === 'string') || text.length === 0) {
    // Throwing an HttpsError so that the client gets the error details.
    throw new functions.https.HttpsError('invalid-argument', 'The function must be called with ' +
        'one arguments "text" containing the message text to add.');
  }
  // Checking that the user is authenticated.
  if (!context.auth) {
    // Throwing an HttpsError so that the client gets the error details.
    throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
        'while authenticated.');
  }

但我不确定我应该为 sendFollowerNotification 示例发送什么:

https://github.com/firebase/functions-samples/tree/master/fcm-notifications

exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}')
    .onWrite((change, context) => {
      const followerUid = context.params.followerUid;
      const followedUid = context.params.followedUid;
      // If un-follow we exit the function.
      if (!change.after.val()) {
        return console.log('User ', followerUid, 'un-followed user', followedUid);
      }

我的意思是......假设用户已登录并拥有firebase UID并且在数据库中(当有人登录时,我的应用程序会自动创建一个firebase用户)......看起来sendFollowerNotification只是从实时数据库中获取所有内容。

那么我在下面放什么呢?:

.call(data)

我如何检索我要关注的用户的 UID?对于已登录并使用该应用程序的人...我显然已经拥有该用户的 UID、令牌和其他所有内容...但我不确定如何为即将被关注的用户检索该信息...如果那有意义的话。

我在整个互联网上搜索过,但从未找到使用新的 post 12.0.0 方法在 android 应用程序中使用这种特殊函数调用的示例。所以我很想知道正确的语法应该是什么。

标签: androidfirebasefirebase-realtime-database

解决方案


好的!这个真的激怒了我试图弄清楚......事实证明你根本不需要调用“sendFollowerNotification”......它所做的只是监听 Firebase Realtime Database 的变化。如果您更改 sendFollowerNotification 正在查找的语法...它会自动发送通知。

在“sendFolwerNotification”中根本没有将用户写入实时数据库的调用。我实际上在登录时处理这个:

private DatabaseReference mDatabase; //up top

mDatabase = FirebaseDatabase.getInstance().getReference(); //somewhere in "onCreate"

final String userId = mAuth.getUid();

String refreshedToken = FirebaseInstanceId.getInstance().getToken();

mDatabase.child("users").child(userId).child("displayName").setValue(name);
mDatabase.child("users").child(userId).child("notificationTokens").child(refreshedToken).setValue(true);
mDatabase.child("users").child(userId).child("photoURL").setValue(avatar);

然后,当一个用户关注另一个用户时,我也将其写入实时数据库:

mDatabase.child("followers").child(user_Id).child(follower_id).setValue(true);

就是这样!第二个新的关注者被添加到实时数据库中...... sendFollwerNotification 将自动发送通知。您只需要在您的应用程序中设置一个侦听器来接收消息,并且一旦用户点击已收到的消息并且您完成后,它应该将您的用户重定向到哪里。


推荐阅读