10
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

お題は不問!Qiita Engineer Festa 2023で記事投稿!

【Unity】FirebaseCloudMessagingでAndroid端末PushTokenが受信出来なかった件

Last updated at Posted at 2023-07-18

TL;DR

FirebaseMessaging.GetTokenAsync() で現在のトークンを取得するようにしよう!

事のいきさつ

Unityを使ったプロダクトでFirebaseUnitySDKを利用していたのですが、CloudMessagingを利用する際、
Android端末でのみPushTokenが受け取れない事がある という事象が起きていました。

調査の結果、アプリの初回起動時のみTokenを受信出来ていてそれ以降はアプリを入れ直すまで受信しないという状態になっていました。
iOSでは毎回来ていたので開発中に不具合の検知が遅れてしまいました。

その時の実装イメージ

FirebaseProvider.cs
public FirebaseProvider()
{
    FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
    {
        var dependencyStatus = task.Result;
        if (dependencyStatus == DependencyStatus.Available) {
            // Create and hold a reference to your FirebaseApp,
            // where app is a Firebase.FirebaseApp property of your application class.
            AppInstance = FirebaseApp.DefaultInstance;

            // Set a flag here to indicate whether Firebase is ready to use by your app.
            FirebaseMessaging.TokenReceived += FirebaseMessagingOnTokenReceived;
            FirebaseMessaging.MessageReceived += FirebaseMessagingOnMessageReceived;
            
        } else {
           Debug.LogError("Firebase Initialize Failed.");
        }
        
    });
}

private void FirebaseMessagingOnMessageReceived(object sender, MessageReceivedEventArgs e)
{
}

private void FirebaseMessagingOnTokenReceived(object sender, TokenReceivedEventArgs e)
{
//ここでPushTokenを受け取ってサーバーに渡してた
}

解決策

GetTokenAsyncを使おう
https://firebase.google.com/docs/reference/unity/class/firebase/messaging/firebase-messaging#gettokenasync

このメソッドをコールすることで現在のトークンを取得することができます。
このトークンを使うことで解決しました

その後の実装例

FirebaseProvider.cs
//このメソッドを叩いてTokenを取得し、サーバーに送る
public async UniTask<string> GetFcmTokenAsync(CancellationToken cancellationToken)
{
    string ret = string.Empty;
    if (AppInstance != null)
    {
        cancellationToken.ThrowIfCancellationRequested();
        ret = await FirebaseMessaging.GetTokenAsync();
        cancellationToken.ThrowIfCancellationRequested();
    }
    
    Debug.Log($"Firebase PushToken {ret}");
    return ret;
}

10
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?