Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/222.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 用于生成firebase用户到用户通知的脚本_Android_Firebase_Google Cloud Functions_Firebase Cloud Messaging_Firebase Notifications - Fatal编程技术网

Android 用于生成firebase用户到用户通知的脚本

Android 用于生成firebase用户到用户通知的脚本,android,firebase,google-cloud-functions,firebase-cloud-messaging,firebase-notifications,Android,Firebase,Google Cloud Functions,Firebase Cloud Messaging,Firebase Notifications,(抱歉英语不好) 我正在寻找一种在Android中实现用户对用户通知的方法。 系统必须捕获数据库中的新子事件,读取数据并将通知发送到目标 数据库的结构如下所示: notificationRequests $pushid message: "You have a new request! Open the app" userId: "sadbijasuobru112u4124u21b" //user destinat

(抱歉英语不好) 我正在寻找一种在Android中实现用户对用户通知的方法。 系统必须捕获数据库中的新子事件,读取数据并将通知发送到目标

数据库的结构如下所示:

notificationRequests
    $pushid
      message: "You have a new request! Open the app"
      userId: "sadbijasuobru112u4124u21b"      //user destination id
通过在网络上做一些研究,我发现了使用主题信息的可能性。 因此,在调用MainActivity之前,我在我的LoginActivity中添加了以下内容:

    FirebaseMessaging.getInstance().subscribeToTopic("users_topic$uid")
                    .addOnCompleteListener {
                        Log.d("LoginActivity", "User registered")
                    }
代码是有效的。我可以从控制台发送通知

就像我之前说的,我需要自动消息。 我在网上找到了这段代码,但它不起作用

var firebase = require('firebase-admin');
var request = require('request');

var API_KEY = "Firebase Cloud Messaging Server API key"

// Fetch the service account key JSON file contents
var serviceAccount = require("./serviceAccountKey.json");

// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
  credential: firebase.credential.cert(serviceAccount),
  databaseURL: "https://appname.firebaseio.com/"
});
ref = firebase.database().ref();

function listenForNotificationRequests() {
  var requests = ref.child('notificationRequests');
  requests.on('child_added', (requestSnapshot) => {
    var request = requestSnapshot.val();
    sendNotificationToUser(
      request.userId, 
      request.message,
      () => {
        requestSnapshot.ref.remove();
      }
    );
  }, (error) => {
    console.error(error);
  });
}

function sendNotificationToUser(userID, message, onSuccess) {
  request({
    url: 'https://fcm.googleapis.com/fcm/send',
    method: 'POST',
    headers: {
      'Content-Type' :' application/json',
      'Authorization': 'key='+API_KEY
    },
    body: JSON.stringify({
      notification: {
        title: message
      },
      to : '/topics/users_topic'+userID
    })
  }, (error, response, body) => {
    if (error) { console.error(error); }
    else if (response.statusCode >= 400) { 
      console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage); 
    }
    else {
      onSuccess();
    }
  });
}

// start listening
listenForNotificationRequests();
我已经在index.js中为部署实现了这段代码。我也写了整个文件,而不是要求它,但它总是一样的

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

exports.sendNotifications = functions.https.onRequest((request, response) => {
  require('./sendNotifications.js')
})
有什么建议吗? 谢谢你的海带

编辑

是否需要配置计费帐户?如果是,我如何使用免费计划

是否需要配置计费帐户?如果是,我如何使用免费计划

请参阅,但简而言之:从节点10开始,您需要输入计费信息才能使用云功能

您可以使用Node 8直到明年初,而无需输入计费信息


请注意,输入计费信息并不一定意味着您必须付费,因为云功能有一个相当重要的免费层。

问题是我打电话给一个外部站点。我是这样解决的:

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

var firebase = require('firebase-admin');

// Fetch the service account key JSON file contents
var serviceAccount = require("./serviceAccountKey.json");

// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
  credential: firebase.credential.cert(serviceAccount),
  databaseURL: "https://appname.firebaseio.com/"
});

exports.sendNotifications = functions.database.ref('/notificationRequest/{pushId}')
  .onCreate( (change, context) => {
    var uid = change.child('userId').val()
    var notificationMessage = change.child('message').val()

    var userTopic = 'users_topic'+uid

    var payload = {
      data: {
        message: notificationMessage
      }
    };

    var options = {
      priority: 'high',
      timeToLive: 60 * 60 * 24,
      collapseKey: 'notification'
    };

    firebase.messaging().sendToTopic(userTopic, payload, options)
      // eslint-disable-next-line promise/always-return
      .then((response) => {
        console.log('Done', response);
      })
      .catch((error) => {
        console.log('Error: ', error);
      });

    return change.ref.remove();
  });