firebase OnMessageReceived Not Working当应用程序在后台处于非活动状态时

mgdq6dx1  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(152)

当我完全关闭应用程序,收到一个警报,并点击它,它进入OnMessageReceived好,相反,如果你离开应用程序在后台不活动,并收到一个警报,并点击它,它不会工作.
嗯。。我试着通过删除通知并只在数据中放入信息来发送警报,但什么也没有来。
处理消息的Unity脚本。

using System.Collections.Generic;
using UnityEngine;
using Firebase.Messaging;
using Firebase;
using UnityEngine.Networking;
using Firebase.Auth;

public class FirebaseMessagingController : MonoBehaviour
{
    public static FirebaseMessagingController Instance { get; private set; }

    //public string firebaseFunctionsUrl;

    public FirebaseRealtimeDatabase firebaseRealtimeDatabase;

    public FirebaseUser currentUser;

    public string userId;

    public string userName;

    private void OnEnable()
    {
        SubscribeEvent();
    }

    private void OnDisable()
    {
        UnSubscribeEvent();
    }

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void SubscribeEvent()
    {
        FirebaseMessaging.TokenReceived += OnTokenReceived;
        FirebaseMessaging.MessageReceived += OnMessageReceived;
    }

    public void UnSubscribeEvent()
    {
        FirebaseMessaging.TokenReceived -= OnTokenReceived;
        FirebaseMessaging.MessageReceived -= OnMessageReceived;
    }

    public async void GetTokenAsync()
    {
        var task = FirebaseMessaging.GetTokenAsync();

        await task;

        if (task.IsCompleted)
        {
            Debug.Log("GET TOKEN ASYNC " + task.Result);
            firebaseRealtimeDatabase.StartCoroutineSaveUserIdToken(task.Result);
        }
    }

    // 디바이스 토큰 수신 이벤트 핸들러
    private void OnTokenReceived(object sender, TokenReceivedEventArgs token)
    {
        Debug.Log($"디바이스 토큰: {token.Token}");

        if (!PlayerPrefs.HasKey("Token"))
        {
            firebaseRealtimeDatabase.StartCoroutineSaveUserIdToken(token.Token);

            PlayerPrefs.SetString("Token", token.Token);
        }
    }

    private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
    {
        Debug.Log("Received a new message");

        e.Message.Data.TryGetValue("click_action", out var clickAction);

        Debug.Log("clickAction : " + clickAction);

        if (clickAction == "********_MESSAGE")
        {
          
            Debug.Log("*********_MESSAGE");

            // 딥링크 처리
            if (e.Message.Data.TryGetValue("deep_link", out var deepLink))
            {
                Debug.Log("deepLink Process : " + deepLink);
                DynamicDeepLinkController.Instance.onDeepLinkActivated(deepLink);
                
            }
        }
    }

    public void SendMessage(string latitude, string longitude)
    {
        // Firebase Functions 엔드포인트 URL
        string url = "https://************.cloudfunctions.net/sendMessage";
        string message = $"{userName} left a message at {latitude},{longitude}";

        // 요청에 필요한 데이터 구성
        var formData = new WWWForm();
        formData.AddField("writerUid", DynamicDeepLinkController.Instance.writerUid);
        formData.AddField("userId", userId);
        formData.AddField("userName", userName);
        formData.AddField("latitude", latitude);
        formData.AddField("longitude", longitude);
        formData.AddField("message", message);

        // 요청 보내기
        UnityWebRequest request = UnityWebRequest.Post(url, formData);
        request.SendWebRequest();

        // 응답 처리
        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError("Failed to send message: " + request.error);
        }
        else
        {
            if (request.responseCode >= 200 && request.responseCode < 300)
            {
                Debug.Log("Message sent successfully");
            }
            else
            {
                Debug.LogError("Failed to send message. Response code: " + request.responseCode);
            }
        }
    }
}

Firebase函数的类型脚本如下。

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import serviceAccount from "../service-account.json";

// Firebase Admin SDK 초기화
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount as admin.ServiceAccount),
  databaseURL: "https://*********-default-rtdb.firebaseio.com/",
});

// FCM 인스턴스 가져오기
const fcm = admin.messaging();

export const sendMessage = functions.https.onRequest(async (req, res) => {
  const writerUid = req.body.writerUid as string;
  const userId = req.body.userId as string;
  const userName = req.body.userName as string;
  const latitude = req.body.latitude as string;
  const longitude = req.body.longitude as string;
  const receivedMessage = req.body.message as string;

  const userNameReplace = userName.replace(" ", "+");

  // 사용자 아이디를 기반으로 토큰 검색
  const tokenSnapshot =
  await admin.database().ref(`users/${writerUid}/token`).once("value");
  const token = tokenSnapshot.val();

  functions.logger.log(`writerUid : ${writerUid}`);
  functions.logger.log(`userId : ${userId}`);
  functions.logger.log(`userName : ${userName}`);
  functions.logger.log(`token : ${token}`);
  functions.logger.log(`latitude : ${latitude}`);
  functions.logger.log(`longitude : ${longitude}`);
  functions.logger.log(`receivedMessage : ${receivedMessage}`);
  functions.logger.log(`userNameReplace : ${userNameReplace}`);

  if (!token) {
    res.status(404).send("User token not found");
    return;
  }

  functions.logger.log(`click_action : ********://message?${latitude}?${longitude}?${userId}?${userNameReplace}`);

  // 메시지 페이로드 생성
  const message = {
    notification: {
      title: userName,
      body: receivedMessage,
    },
    data: {
      // title: userName,
      // body: receivedMessage,
      click_action: "********_MESSAGE",
      deep_link: `********://message?${latitude}?${longitude}?${userId}?${userNameReplace}`,
    },
    token: token,
  };

  // 메시지 보내기
  try {
    await fcm.send(message);
    functions.logger.log("메시지를 성공적으로 보냈습니다.");
    res.status(200).send("Message sent successfully");
  } catch (error) {
    functions.logger.log("메시지 보내기 중 오류가 발생했습니다:", error);
    res.status(500).send("Error sending message");
  }
});
zzzyeukh

zzzyeukh1#

嗯..我试图通过删除通知发送警报
从以下摘录的外观来看,通知字段似乎仍然是满的。您是否在其他地方发送没有通知字段的消息?如果是,请发布。

// 메시지 페이로드 생성
  const message = {
    notification: {
      title: userName,
      body: receivedMessage,
    },
    data: {
      // title: userName,
      // body: receivedMessage,
      click_action: "********_MESSAGE",
      deep_link: `********://message?${latitude}?${longitude}?${userId}?${userNameReplace}`,
    },
    token: token,
  };

相关问题