android中未收到FCM通知,尽管FCM控制台表示交付成功

android中未收到FCM通知,尽管FCM控制台表示交付成功,android,firebase,firebase-cloud-messaging,google-cloud-functions,Android,Firebase,Firebase Cloud Messaging,Google Cloud Functions,我和其他用户并没有收到通知,尽管控制台说这是成功的。我想在新文章发布时通知所有用户。因此,无论何时在发布的节点中有一个新的密钥,都应该触发fcm函数。 以下是我的FCM功能: 'use strict' const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().fire

我和其他用户并没有收到通知,尽管控制台说这是成功的。我想在新文章发布时通知所有用户。因此,无论何时在发布的节点中有一个新的密钥,都应该触发fcm函数。

以下是我的FCM功能:

    'use strict'
    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);
    exports.sendNotification = functions.database.ref('/published/{msg_id}').onWrite(event => { 
      const snapshot = event.data;
      // Only send a notification when a new message has been created.
      if (snapshot.previous.val()) {
        return;
      }
      const msg_id = event.params.msg_id;

      const msg_val=admin.database().ref(`messages/${msg_id}`).once('value');
      return msg_val.then(msgResult =>{
        const msg_title=msgResult.val().title;
        const user_id=msgResult.val().userId;
        console.log('msg title is',msg_title);
         console.log('We have a new article : ', msg_id);
          const payload={

            data : {
              title:"New Article",
              body: msg_title,
              msgid : msg_id,
              userid : user_id

            }
        };

     const getDeviceTokensPromise = admin.database().ref('/FCMToken').once('value');
     return Promise.all([getDeviceTokensPromise, msg_title]).then(results => {

       const tokensSnapshot = results[0];
        const msgi = results[1];

      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("tokenslist",tokensSnapshot.val());

       const tokens= Object.keys(tokensSnapshot.val()).map(e => tokensSnapshot.val()[e]);
       //var values = Object.keys(o).map(e => obj[e])]
       const keyLists = Object.keys(tokensSnapshot.val());
       console.log("keyList",keyLists[0]);

         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);
                if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {
                  const kk=tokensSnapshot.ref.child(keyLists[index]);
                  console.log("deleted is",kk);
                  tokensToRemove.push(tokensSnapshot.ref.child(keyLists[index]).remove());
             // tokensToRemove.push(tokensSnapshot.ref.child((tokensSnapshot.child(tokens[index]).key).remove()));

            }
              // Cleanup the tokens who are not registered anymore.

            }
            else
            {
              console.log("Successful sent to",tokens[index]);
            }
          });
          return Promise.all(tokensToRemove);
        });

    });
    });
    });
 This is my FirebaseMessagingService :

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";

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

        String notificatication_type = remoteMessage.getData().get("title");
        Log.d("getnot",notificatication_type);
        String msgTitle = remoteMessage.getData().get("body");
        String user = remoteMessage.getData().get("userName");
        String teller=remoteMessage.getData().get("userteller");
        String photoloader=remoteMessage.getData().get("photoid");
        String notification_body;
        String notification_title=null;

        if (user != null) {
            notification_body = "New " + notificatication_type + " on your article " + msgTitle + " by " + user;
            notification_title = "New" + notificatication_type;

        } else {

            if(teller!=null)
            {
                notification_body = notificatication_type + " " + msgTitle;
                notification_title="New Audio";
            }
            else if(photoloader!=null)
            {
                notification_body = notificatication_type + " " + msgTitle;
                notification_title = "New Photo";
            }

            else {
                notification_body = notificatication_type + " " + msgTitle;
                notification_title = "New Article";
            }
        }

       // Log.d("notification_body", notification_body);
        //TODO new article notification
        // String click_action = remoteMessage.getNotification().getClickAction();
        String mid = remoteMessage.getData().get("msgid");
        Log.d("checkmid",mid);
        String uid;

        if(teller!=null)
        {
             uid = remoteMessage.getData().get("userteller");
        }

        else if(photoloader!=null)
        {
            uid=remoteMessage.getData().get("photoid");
        }
        else
       uid = remoteMessage.getData().get("userid");
        Map<String, String> params = new HashMap<String, String>();
        //params = remoteMessage.getData().get("msgid"),remoteMessage.getData().get("userid");
        params.put("msgid", mid);
        params.put("userid", uid);
        JSONObject object = new JSONObject(params);
      //  Log.d("JSON_OBJECT", object.toString());

        //setBadge(getApplicationContext(), countNo, notification_body, object);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this,"sam")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle(notification_title)
                        .setContentText(notification_body)
                        .setAutoCancel(true);
        //TODO CHANGED HERE INTENT
        Intent resultIntent;
        if(teller==null&&photoloader==null) {

             resultIntent = new Intent(this, ArticleDetail.class);
            resultIntent.setAction(Long.toString(System.currentTimeMillis()));
            // Log.d("getAction",click_action);
            resultIntent.putExtra("bkgnotification", object.toString());
        }
        else if(photoloader!=null)
        {
            resultIntent = new Intent(this, DisplayPhoto.class);
            resultIntent.setAction(Long.toString(System.currentTimeMillis()));
            // Log.d("getAction",click_action);
            resultIntent.putExtra("bkgnotification", object.toString());
        }
        else
        {
            resultIntent = new Intent(this, PlayAudioActivity.class);
            resultIntent.setAction(Long.toString(System.currentTimeMillis()));
            // Log.d("getAction",click_action);
            resultIntent.putExtra("bkgnotification", object.toString());
        }
        //  resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
        int mNotificationId = (int) System.currentTimeMillis();
        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
        mBuilder.setContentIntent(resultPendingIntent);

// Sets an ID for the notification

// Gets an instance of the NotificationManager service
        NotificationManager mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("notify_001",
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            mNotifyMgr.createNotificationChannel(channel);
        }
// Builds the notification and issues it.
        mNotifyMgr.notify(mNotificationId, mBuilder.build());

        // TODO: Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated.

        // FirebaseDatabase db=FirebaseDatabase.getInstance();
        // DatabaseReference dbref=db.getReference("notification");
        //dbref.removeValue();
    }
“使用严格的”
const functions=require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification=functions.database.ref('/published/{msg_id}').onWrite(event=>{
const snapshot=event.data;
//仅在创建新邮件时发送通知。
if(snapshot.previous.val()){
回来
}
const msg_id=event.params.msg_id;
const msg_val=admin.database().ref(`messages/${msg_id}`)。once('value');
返回msg_val.then(msgResult=>{
const msg_title=msgResult.val().title;
const user_id=msgResult.val().userId;
日志('msg title is',msg_title);
log('我们有一篇新文章:',msg_id);
常数有效载荷={
数据:{
标题:“新文章”,
正文:msg_标题,
msgid:msg_id,
userid:user\u id
}
};
const getDeviceTokenPromise=admin.database().ref('/FCMToken')。once('value');
返回承诺。全部([GetDeviceTokenPromise,msg_title])。然后(结果=>{
const tokensSnapshot=结果[0];
常数msgi=结果[1];
如果(!tokensSnapshot.hasChildren()){
return console.log('没有要发送的通知令牌');
}
log('There',tokensSnapshot.numChildren(),'tokens to send notification to');
log(“tokenslist”,tokensSnapshot.val());
const tokens=Object.key(tokensSnapshot.val()).map(e=>tokensSnapshot.val()[e]);
//var values=Object.keys(o.map)(e=>obj[e])]
const keyLists=Object.keys(tokensSnapshot.val());
log(“keyList”,keyLists[0]);
返回admin.messaging(){
//对于每条消息,检查是否有错误。
常量tokensToRemove=[];
response.results.forEach((结果,索引)=>{
常量错误=result.error;
如果(错误){
console.error('Failure sending notification to',tokens[index],error);
if(error.code==='消息传递/注册令牌无效'| | error.code==='消息传递/注册令牌未注册'){
const kk=tokensSnapshot.ref.child(键列表[索引]);
console.log(“已删除”,kk);
tokensToRemove.push(tokensSnapshot.ref.child(keyLists[index]).remove());
//tokensToRemove.push(tokensSnapshot.ref.child((tokensSnapshot.child(tokens[index]).key.remove());
}
//清理不再注册的令牌。
}
其他的
{
log(“成功发送到”,令牌[索引]);
}
});
归还承诺。全部(tokensToRemove);
});
});
});
});
这是我的FirebaseMessagingService:
公共类MyFirebaseMessagingService扩展了FirebaseMessagingService{
私有静态最终字符串TAG=“FCM服务”;
@凌驾
收到消息时公共无效(RemoteMessage RemoteMessage){
super.onMessageReceived(remoteMessage);
String notification_type=remoteMessage.getData().get(“title”);
Log.d(“getnot”,通知类型);
字符串msgTitle=remoteMessage.getData().get(“正文”);
字符串user=remoteMessage.getData().get(“用户名”);
String teller=remoteMessage.getData().get(“userteller”);
字符串photoloader=remoteMessage.getData().get(“photoid”);
字符串通知单元体;
字符串通知_title=null;
如果(用户!=null){
由“+用户”在您的文章“+msgTitle+”上通知“\u body=“New”+通知类型+”;
通知_title=“新建”+通知类型;
}否则{
if(出纳员!=null)
{
通知正文=通知类型+“”+msgTitle;
通知_title=“新音频”;
}
else if(photoloader!=null)
{
通知正文=通知类型+“”+msgTitle;
通知_title=“新照片”;
}
否则{
通知正文=通知类型+“”+msgTitle;
通知_title=“新条款”;
}
}
//Log.d(“通知主体”,通知主体);
//TODO新文章通知
//String click_action=remoteMessage.getNotification().getClickAction();
String mid=remoteMessage.getData().get(“msgid”);
Log.d(“检查中间”,中间);
字符串uid;
if(出纳员!=null)
{
uid=remoteMessage.getData().get(“userteller”);
}
else if(photoloader!=null)
{
uid=remoteMessage.getData().get(“photoid”);
}
其他的
uid=remoteMessage.getData().get(“userid”);
Map params=新的HashMap();
//params=remoteMessage.getData().get(“msgid”),remoteMessage.getData().get(“userid”);
参数put(“msgid”,mid);
参数put(“userid”,uid);
JSONObject对象=新的JSONObject(参数);
//Log.d(“JSON_对象”,OBJECT.toString());
//setBadge(getApplicationContext(),countNo,notification_body,object);
通知相容建筑商mBuilder=
新建NotificationCompat.Builder(此“sam”)
.setSmallIcon(R.mipmap.ic_启动器)
.setContentTitle(通知标题)