Firebase功能 - 设备令牌为空

时间:2017-09-12 17:54:22

标签: android node.js firebase firebase-realtime-database

我需要帮助,我一整天都在寻找解决方案,但我无法解决问题,下面的代码无法读取设备令牌。

下面包含我的数据库结构。我设法接收日志:'我们为您准备了新消息。当我添加新帖子但我收到了日志" 有没有通知令牌发送给。"这意味着即使已有设备令牌也无法检测到设备令牌。我做错了什么?



{

  "Newsv2" : {
"All" : {

  "-Ktr7ZkuChCjsUIMb_4f" : {
    "title" : "",
    "type" : "",
  }
},

 "Usersv2" : {

"h0RzzpdO7nZVLpAR4fi7xRWUqsT2" : {
  "device_token" : "",
  "name" : "",
  "user_no" : ""
}
  },
  
  }



/--News
    --All
       --name
       --desc

/--Usersv2
    --{userID}
      --device_token


exports.sendNotif = functions.database.ref('/Newsv2/All/{newsID}').onWrite(event => {
  const newsID = event.params.newsID;
  const userID = event.params.userID;

  if (!event.data.val()) {
    return console.log('News! ', newsID);
  }
  console.log('We have a new News for you!',newsID);

  // Get the list of device notification tokens.
  const getDeviceTokensPromise = admin.database().ref(`/Usersv2/${userid}/device_token`).once('value');

  return Promise.all([getDeviceTokensPromise]).then(results => {
    const tokensSnapshot = results[0];
    //const follower = results[1];

    // Check if there are any device tokens.
    if (!tokensSnapshot.hasChildren()) {
      return console.log('There are no notification tokens to send to.');
    }
    console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
    //console.log('Fetched follower profile', follower);

    // Notification details.
    const payload = {
      notification: {
        title: 'Test Message',
        body: '',
        icon: ''
      }
    };

    // Listing all tokens.
    const tokens = Object.keys(tokensSnapshot.val());

    // Send notifications to all tokens.
    return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const tokensToRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens who are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
              error.code === 'messaging/registration-token-not-registered') {
            tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });
      return Promise.all(tokensToRemove);
    });
  });
});




1 个答案:

答案 0 :(得分:0)

要获取设备令牌,我会在用户注册或登录时将其存储在我的firebase数据库中。

    private DatabaseReference mUserDatabase;
    mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users/");
    //and if the login/register is successful
    mUserDatabase.child("device_token").setValue(deviceToken).addOnSuccessListener(new OnSuccessListener<Void>() {
                                                    @Override
                                                    public void onSuccess(Void aVoid) {
                                                    Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
                                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
                                                    application.startActivity(intent);
                                                }
                                            });

至于我的火力棒功能:

const deviceToken = admin.database().ref(`/Users/${unique_id}/device_token`).once('value');