firebase坏令牌号中的设备到设备通知

时间:2018-04-20 15:55:17

标签: android firebase firebase-cloud-messaging firebase-notifications

我们正在尝试在firebase中实现设备到设备通知系统,但我们遇到一种奇怪的现象,我们有时会收到通知,有时我们却没有。不幸的是,我们无法确定这种场合之间的区别 然而,我们在firebase文档中看到我们需要为设备令牌更改实现服务侦听器(并将其添加到清单),我们认为问题可能是我们没有通知该服务器进行更改。 / p>

firebase功能代码:

/*
 * Functions SDK : is required to work with firebase functions.
 * Admin SDK : is required to send Notification using functions.
 */

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


/*
 * 'OnWrite' works as 'addValueEventListener' for android. It will fire the function
 * everytime there is some item added, removed or changed from the provided 'database.ref'
 * 'sendNotification' is the name of the function, which can be changed according to
 * your requirement
 */

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite(event => {


  /*
   * You can store values as variables from the 'database.ref'
   * Just like here, I've done for 'user_id' and 'notification'
   */

  const user_id = event.params.user_id;
  const notification_id = event.params.notification_id;

  console.log('We have a notification from : ', user_id);

  /*
   * Stops proceeding to the rest of the function if the entry is deleted from database.
   * If you want to work with what should happen when an entry is deleted, you can replace the
   * line from "return console.log.... "
   */

  if(!event.data.val()){

    return console.log('A Notification has been deleted from the database : ', notification_id);

  }

  /*
   * 'fromUser' query retreives the ID of the user who sent the notification
   */

  const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');

  return fromUser.then(fromUserResult => {

    const from_user_id = fromUserResult.val().from;

    console.log('You have new notification from  : ', from_user_id);

    /*
     * The we run two queries at a time using Firebase 'Promise'.
     * One to get the name of the user who sent the notification
     * another one to get the devicetoken to the device we want to send notification to
     */

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

    return Promise.all([userQuery, deviceToken]).then(result => {

      const userName = result[0].val();
      const token_id = result[1].val();

      /*
       * We are creating a 'payload' to create a notification to be sent.
       */

      const payload = {
        notification: {
          title : "New Friend Request",
          body: `${userName} has sent you request`,
          icon: "default",
          click_action : "in.tvac.akshaye.lapitchat_TARGET_NOTIFICATION"
        },
        data : {
          from_user_id : from_user_id
        }
      };

      /*
       * Then using admin.messaging() we are sending the payload notification to the token_id of
       * the device we retreived.
       */

      return admin.messaging().sendToDevice(token_id, payload).then(response => {

        console.log('This was the notification Feature');

      });

    });

  });

});

发送通知功能

private void sendNotificationToCostumer() {
        final HashMap<String, String> notificationData = new HashMap<>();
        notificationData.put("from", currentUser.getUid());
        notificationData.put("type", "bid request");

        FirebaseDatabase.getInstance().getReference().child("notifications").child(curJobInflated.second.getPersonUid())
                .push().setValue(notificationData).
                addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(MapActivity.this, "sending notification to the costumer",
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }

firebase实例服务(这是一个复制的代码,这里可能缺少必要的代码

package com.rubz.dvir.rubz;

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.google.firebase.messaging.FirebaseMessaging;

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";
    private static final String FRIENDLY_ENGAGE_TOPIC = "friendly_engage";

    /**
     * The Application's current Instance ID token is no longer valid and thus a new one must be requested.
     */
    @Override
    public void onTokenRefresh() {
        // If you need to handle the generation of a token, initially or after a refresh this is
        // where you should do that.
        String token = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "FCM Token: " + token);
    }
}

Firebase消息传递服务实现

package com.rubz.dvir.rubz;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import com.google.firebase.messaging.RemoteMessage;

public class FirebaseMessagingService extends  com.google.firebase.messaging.FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        String messageTitle = remoteMessage.getNotification().getTitle();
        String messageBody = remoteMessage.getNotification().getBody();

        //get the click action
        String click_action = remoteMessage.getNotification().getClickAction();
        String dataMessage = remoteMessage.getData().get("message");
        //String dataFrom = remoteMessage.getData().get("from_id");

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
                .setSmallIcon(R.drawable.menu_icon)
                .setContentTitle("new notification")
                .setContentText("Hi your bid has accepted")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        int mNotificationId = (int)System.currentTimeMillis();
        NotificationManager mNotifyMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);


        Intent resultIntent = new Intent(click_action);
        resultIntent.putExtra("message", dataMessage);
        //resultIntent.putExtra("dataFrom", dataFrom);

        PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder.setContentIntent(resultPendingIntent);
        mNotifyMgr.notify(mNotificationId, mBuilder.build());
    }
}

相关服务声明出现在清单中。

更新:在调试模式下测试时,我们会在“已接收”设备中收到通知,但不知何时通知不会膨胀。

update2:问题根本与firebase无关,而是与SDK&gt;中的通知用法有关26 见Notification Not showing

1 个答案:

答案 0 :(得分:1)

index.js文件中,您有:

const payload = {
    notification: {
      title : "New Friend Request",
      body: `${userName} has sent you request`,
      icon: "default",
      click_action : "in.tvac.akshaye.lapitchat_TARGET_NOTIFICATION"
    },
    data : {
      from_user_id : from_user_id
    }
  };

这里您发送的是通知有效负载,只会在手机处于前台(打开并且您正在使用它)时发送通知。因此,如果手机处于后台,即使在firebase控制台中您具有状态"ok"

,您也不会收到通知

为了能够获得通知,当手机处于后台和前台时,您需要使用数据有效负载,例如:

data: {
      title : "New Friend Request",
      body: `${userName} has sent you request`,
      icon: "default",
      click_action : "in.tvac.akshaye.lapitchat_TARGET_NOTIFICATION"
    },

然后在FCM中,您需要接收该数据:

if (remoteMessage.getData().size() > 0) {

    title = remoteMessage.getData().get("title");
    body = remoteMessage.getData().get("body");
}

更多信息:

https://firebase.google.com/docs/cloud-messaging/concept-options