firebase / quickstart-unity

Firebase Quickstart Samples for Unity
https://firebase.google.com/games
Apache License 2.0
822 stars 425 forks source link

Android Firebase 8.0.0 TokenReceived called only on application reinstall #1088

Open maniaks1 opened 3 years ago

maniaks1 commented 3 years ago

[REQUIRED] Please fill in the following fields:

[REQUIRED] Please describe the question here:

After updating the Firebase Unity SDK from version 7.1.0 to version 8.0.0, the TokenReceived event on android stopped being called after each initialization. Now now the event comes only once when installing the application. On iOS, everything is still correct. A direct call to FirebaseMessaging.GetTokenAsync returns the push token correctly.

Is this a bug or a new behavior and now we need to get a token like in android sdk and save it until the next change?

=======================================================================================

Dependencies:

com.adcolony:sdk:4.5.0
com.android.installreferrer:installreferrer:2.1
com.android.support:support-compat:26.1.0
com.android.support:support-v4:26.1.0
com.facebook.android:audience-network-sdk:6.5.0
com.google.android.gms:play-services-ads:20.1.0
com.google.android.gms:play-services-ads-identifier:17.0.0
com.google.android.gms:play-services-base:17.6.0
com.google.android.gms:play-services-basement:17.5.0
com.google.firebase:firebase-analytics:19.0.0
com.google.firebase:firebase-analytics-unity:8.0.0
com.google.firebase:firebase-app-unity:8.0.0
com.google.firebase:firebase-common:20.0.0
com.google.firebase:firebase-messaging:22.0.0
com.google.firebase:firebase-messaging-unity:8.0.0
com.google.games:gpgs-plugin-support:0.10.12
com.ironsource.adapters:adcolonyadapter:4.3.8
com.ironsource.adapters:admobadapter:4.3.20
com.ironsource.adapters:facebookadapter:4.3.27
com.ironsource.adapters:unityadsadapter:4.3.11
com.ironsource.sdk:mediationsdk:7.1.6
com.tapjoy:tapjoy-android-unitybridge:12.8.1
com.unity3d.ads:unity-ads:3.7.2

We are using manual initialization.

Android manifest:

<service android: name = "com.google.firebase.messaging.MessageForwardingService" android: permission = "android.permission.BIND_JOB_SERVICE" android: exported = "false" />
<meta-data android: name = "firebase_messaging_auto_init_enabled" android: value = "false" />
<meta-data android: name = "firebase_analytics_collection_enabled" android: value = "false" />

Our initialization code:

FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
    DependencyStatus dependencyStatus = task.Result;

    if (dependencyStatus == DependencyStatus.Available)
    {
        m_firebaseInstance = FirebaseApp.DefaultInstance;

        if (PluginManager.Instance.IsAllowRequestNotificationsPermission)
        {
            FirebaseMessaging.TokenReceived += OnTokenReceived;
            FirebaseMessaging.MessageReceived += OnMessageReceived;
            FirebaseMessaging.TokenRegistrationOnInitEnabled = true;
        }
    }
    else
    {
        // ...
    }
});

=======================================================================================

paulinon commented 3 years ago

Hi @maniaks1,

In order to identify what's causing this behavior, could you provide a minimal, reproducible example of your project along with the complete steps taken before facing the issue?

maniaks1 commented 3 years ago

Hi @paulinon!

This behavior is repeated in the test firebase project. Steps to repeat:

As a result, the PushToken comes only on first launch. P.S. I don't know whether it is important or not, but all actions were performed on a debug unsigned build, but on the old version of the SDK everything was fine.

2021-07-08 11 25 12

OrionDev23 commented 3 years ago

I think this also prevents us from subscribing, unsubscribing to/from topics. Reverting back to 7.2.0 seems to fix this problem.

chkuang-g commented 2 years ago

@maniaks1

Thanks for reporting. I think I can reproduce the issue with the following steps.

  1. Build the testapp with Firebase SDK 8.1.0 and install it to a device
  2. Observe the log like Received Registration Token, RequestPermissionAsyn completed and SubscribeAsync completed.
  3. Click on Subscribe button and observe it complete successfully.
  4. Kill the app using system tray and relaunch the app.
  5. Observe no log like Received Registration Token or SubscribeAsync completed
  6. Click on Subscribe button. Observe that the async call never complete.

It does not seem to be related to firebase_messaging_auto_init_enabled.

Also I can confirm that 7.2.0 does not have this issue.

Firebase FCM Unity SDK 8.1.0 depends on the following Android libraries

    implementation 'com.google.android.gms:play-services-base:17.6.0' // Assets/Firebase/Editor/AppDependencies.xml:17
    implementation 'com.google.firebase:firebase-analytics:19.0.0' // Assets/Firebase/Editor/MessagingDependencies.xml:15
    implementation 'com.google.firebase:firebase-app-unity:8.1.0' // Assets/Firebase/Editor/AppDependencies.xml:22
    implementation 'com.google.firebase:firebase-common:20.0.0' // Assets/Firebase/Editor/AppDependencies.xml:13
    implementation 'com.google.firebase:firebase-messaging:22.0.0' // Assets/Firebase/Editor/MessagingDependencies.xml:13
    implementation 'com.google.firebase:firebase-messaging-unity:8.1.0' // Assets/Firebase/Editor/MessagingDependencies.xml:20

Firebase FCM Unity SDK 7.2.0 depends on the following Android libraries:

    implementation 'com.google.android.gms:play-services-base:17.6.0' // Assets/Firebase/Editor/AppDependencies.xml:17
    implementation 'com.google.firebase:firebase-analytics:18.0.3' // Assets/Firebase/Editor/MessagingDependencies.xml:15
    implementation 'com.google.firebase:firebase-app-unity:7.2.0' // Assets/Firebase/Editor/AppDependencies.xml:22
    implementation 'com.google.firebase:firebase-common:19.5.0' // Assets/Firebase/Editor/AppDependencies.xml:13
    implementation 'com.google.firebase:firebase-messaging:21.1.0' // Assets/Firebase/Editor/MessagingDependencies.xml:13
    implementation 'com.google.firebase:firebase-messaging-unity:7.2.0' // Assets/Firebase/Editor/MessagingDependencies.xml:20

As a workaround, you will have to uninstall the Firebase 8.x and install 7.2.0

chkuang-g commented 2 years ago

This also may related to the Android S FCM rework mentioned in b/184368806.

timoberquelle commented 2 years ago

Another workaround is to delete the token and get a new one. The reception of the new token also triggers all previous attempts to subscribe/unsubscribe to/from a topic, so it seems everything is still queued and only proceeds once a token arrives. During an app session where a token arrived, subscribing/ unsubscribing works as intended. After killing and restarting the app, subscribing/ unsubscribing is not working anymore.

Behavior can be reproduced with sample scene.

nostek commented 2 years ago

Another workaround that works for us is to await FirebaseMessaging.GetTokenAsync() It gives the same token as the event on first install, then the same token next times when the event doesn't fire.

Nyankoo commented 2 years ago

It seems that the changelog for 8.3.0 mention this was fixed, but it's still not working for us after updating the SDK. Calling await FirebaseMessaging.GetTokenAsync() still works as a workaround.

hippogamesunity commented 2 years ago

Hi! The same issue, TokenReceived is called only after the first app launch. The workaround is to use GetTokenAsync. image

Firebase 8.1.0 / GPGS 0.10.12 Firebase 8.3.0 / GPGS 0.10.12

hippogamesunity commented 2 years ago

Another sad thing is that MessageReceived also doesn't work. I'll try downgrading to Firebase 7...

OrionDev23 commented 2 years ago

Another sad thing is that MessageReceived also doesn't work. I'll try downgrading to Firebase 7...

Try placing await GetTokenAsync() before Message received ?

hippogamesunity commented 2 years ago

Another sad thing is that MessageReceived also doesn't work. I'll try downgrading to Firebase 7...

Try placing await GetTokenAsync() before Message received ?

Looks like Firebase Test notification doesn't work, but MessageReceived works if I send notifications via HTTP API.

cynthiajoan commented 2 years ago

Fixed in release 8.3.0

Nyankoo commented 2 years ago

@cynthiajoan Like I said above, this is NOT fixed in 8.3.0. Still happening with that version! You can see above that other people still have the issue with 8.3.0, too!

hippogamesunity commented 2 years ago

Yes, NOT fixed.

Nyankoo commented 2 years ago

@paulinon @dconeybe Can someone please re-open or look into this?

paulinon commented 2 years ago

Hi @Nyankoo,

So sorry to hear that the issue wasn't fixed in the latest release. The team is currently working on this.

injeniero commented 2 years ago

@paulinon do you know when will this be fixed?

injeniero commented 2 years ago

I just installed 8.6 and same problem as before.

paulinon commented 2 years ago

Hi @injeniero, I don't have a timeline I can share, but the team is working on this.

lsw1164 commented 2 years ago

Same problem on v8.6.2

hesham-akmal commented 2 years ago

Just spent 3 hours figuring out why topic notification is never received :) await FirebaseMessaging.GetTokenAsync() workaround does NOT work for me

v8.6.2 Unity

OrionDev23 commented 2 years ago

Yes , await FirebaseMessaging.GetTokenAsync() doesn't work for me neither. Still using 7.2.0 please fix this.

tallior commented 2 years ago

Any updates on a fix for this @paulinon ? if there's no fix planned, can you suggest a workaround we could implement?

lsw1164 commented 2 years ago

Any news?

Seanm07 commented 2 years ago

Any confirmation on whether this is fixed in 8.8.0? There's sadly no mention of it in the changelog

dsharabarov commented 2 years ago

I have the same problem in 8.8.0

Guidanel commented 2 years ago

I confirm the issue in 8.8.0: receiving the token via the callback and subscribing to topics only work during the first launch of the app. In subsequent sessions even if I change the subscriptions when the player changes the language of the app SubscribeAsync doesn't have any effect.

The await FirebaseMessaging.GetTokenAsync() workaround works to get a token but doesn't change anything for the subscriptions issue.

Edit: are some of you using 7.2 in the meantime? I'd like to avoid going back to an old version but maybe it cannot be helped for now since there hasn't been any update for a while.

OrionDev23 commented 2 years ago

Anything new about this ? this is a critical bug for me and for others, the ability to subscribe to topics is a must.

Tested on 9.0 still the same problem, is there any workaround ?

Using 7.2 just for this is really messed up

Nyankoo commented 2 years ago

@paulinon Any update?

BielBG commented 2 years ago

I literally almost when crazy before finding the problem, but it also happens to me. Unity 2021.3 and Firebase 9.0.0.

I assume this ain't fixed (which literally makes FCM for Unity useless, like??), is there any reliable workaround for subscribing/unsubscribing to topics and recieving messages/notifications? (other than downgrading to 7.2, which I really want to avoid).

Thank you.

BielBG commented 2 years ago

Long ago (like 3-4 years), when upgrading Scripting Backend or Api Compatibility Level in Unity (when they changed the .NET to 4.x if I remember correctly), I had a similar issue: suddently, some functions were not working: not showing in the logs, even with Logcat, even though I added manual "Debug.Log" before & inside it to prove it was being correctly called, and found out it was not working because it was not being called in the main thread. In the Firebase Documentation the following is specified under the function "[System.Threading.Tasks.Task] SubscribeAsync" & others: "Call this function from the main thread. FCM is not thread safe.". Maybe what's happening is that, for whatever reason, it is not being called in the main thread. Does that makes sense? Anyways, could it be possible to force it be called in the main thread? Thank you.

AOEGame commented 1 year ago

same problem in 9.1.0 and 9.2.0

AOEGame commented 1 year ago

anyone fixed this problem?? any workaround?

AOEGame commented 1 year ago

Long ago (like 3-4 years), when upgrading Scripting Backend or Api Compatibility Level in Unity (when they changed the .NET to 4.x if I remember correctly), I had a similar issue: suddently, some functions were not working: not showing in the logs, even with Logcat, even though I added manual "Debug.Log" before & inside it to prove it was being correctly called, and found out it was not working because it was not being called in the main thread. In the Firebase Documentation the following is specified under the function "[System.Threading.Tasks.Task] SubscribeAsync" & others: "Call this function from the main thread. FCM is not thread safe.". Maybe what's happening is that, for whatever reason, it is not being called in the main thread. Does that makes sense? Anyways, could it be possible to force it be called in the main thread? Thank you.

do you find any workarounds? this is a critical bug for me

AOEGame commented 1 year ago

@Guidanel 9.1.0 9.2.0 also has this problem.

do you find any workarounds?

Seanm07 commented 1 year ago

@Guidanel 9.1.0 9.2.0 also has this problem.

do you find any workarounds?

The workaround is to use version 7.2.0 None of the fixes posted here worked for me in any later versions.

AOEGame commented 1 year ago

@Seanm07

Thank you very much for your answer!

I use : Analytics,Crashlytics, Messaging only change Messaging version to 7.2.0?

Seanm07 commented 1 year ago

@Seanm07

Thank you very much for your answer!

I use : Analytics,Crashlytics, Messaging only change Messaging version to 7.2.0?

I'm not sure if it'll let you mix versions without issues, but you can try it and see what happens I guess

timoberquelle commented 1 year ago

The workaround I posted last August is still working as well: Just delete the token and get a new one on when initializing Firebase. Previous request to subsciptions to topics will then be processed as well as they seem to be queued internally:

FirebaseMessaging.DeleteTokenAsync().ContinueWithOnMainThread( task1 => { FirebaseMessaging.GetTokenAsync().ContinueWithOnMainThread( task2 => {

jmcgee412 commented 1 year ago

I can confirm this issue is still present in 9.0.0, and it has now persisted for more than a year since 7.2.0

Also, the release notes for Version 8.2.0 still INCORRECTLY STATE that the Android issue of receiving tokens when initializing the app has been fixed

The issue is that on Android, the TokenRecieved delegate is only fired on the initial install. It never fires any time the app is run after the initial install. The issue also makes it so the Subscribe and Unsubscribe calls do not work. This issue is not present on iOS

The console log shows that the Subscribe or Unsubscribe task is called and just waits forever never receiving a response...and there is also incomplete information with above proposed workarounds I want to help with

Subscription task no response

GetTokenAsync() - Not a workaround GetTokenAsync() is not a workaround by itself. It will receive the current registration token, but it does nothing regarding whatever the connection issue is with the TokenReceived delegate and the Subscribe/Unsubscribe tasks. Those tasks are called and still just wait forever never receiving a response

DeleteTokenAsync() and GetTokenAsync() - Not a workaround This is also not a workaround by itself. If you call DeleteTokenAsync(), wait for it to complete, and then call GetTokenAsync(), it will fix the connection issue, refresh your registration token with a new one, and it will finally fire the TokenReceived delegate. However, all the subscriptions with the previous registration token will be lost

Workaround 1 - DeleteTokenAsync() and GetTokenAsync() and Re-subscribe One less than optimal workaround is to do this every time the client app is opened: Call DeleteTokenAsync(), wait for it to complete, then call GetTokenAsync, wait for it to complete, then re-subscribe to every topic. To prevent potential hanging issues with re-subscribing, you probably need to monitor each subscription task to wait for it to complete before calling the next one, which could take a bit of time if the client app has a lot of topics to subscribe to, all of which could delay the time before your app is ready for the user. This also means your app will need to monitor all subscribe and unsubscribe events to keep a locally held current list of active subscriptions so the client knows what to subscribe to on every use. And you need to hope your logic is sound because there's no way using Unity SDKs for the client app to check in with FCM to confirm what topics it is subscribed to

Workaround 2 - Continue using Firebase 7.2.0 SDKs This is the second less than optimal workaround. This version works as intended for FCM (as far as I know) but you are missing out on the myriad of fixed crashes and bugs that have been worked on since that release. I can't confirm how this will affect things like other packages that had more critical updates since then or having this work on Apple Silicon chips, etc.

My question to Google Firebase Developers Of these two less than optimal workarounds, which one would you say is the better option that has the least unintended consequences and trade-offs? Is it an issue that an app is deleting a token, re-registering, and re-subscribing to potentially thousands of topics every time the app is opened on every client?

..also, it might be helpful to put the workaround you suggest in the Unity Setup documentation or the Unity Troubleshooting notes, as the current notes have not led to a working solution for over a year, and seem to be causing hours and days of troubleshooting for developers until they stumble upon this

XaviSMP commented 1 year ago

Still a problem in version 9.4.0.

I can confirm that workaround number 1 works for me, thank you @jmcgee412 ! As you say, not ideal as you need the client to keep a list of topics to re-suscribe ( and not to mention how slow I presume it is to do the whole process everytime ), but at least it works.

Gnejs commented 1 year ago

Still an issue with 9.6.0. Wasted a few hours troubleshooting this mess. Going back to 7.2.0 since the other workaround is pretty unreasonable.

Seanm07 commented 1 year ago

@cynthiajoan is the firebase team aware this is still an issue or is it planned to be looked into again? 8.3.0 did not fix it as many others in this issue thread have mentioned :(

homu-konamilk commented 1 year ago

Another workaround:

// instead of TokenReceived
FirebaseMessaging.GetTokenAsync().ContinueWith(() => {
    // ...
});

// instead of SubscribeAsync()/UnsubscribeAsync() of Firebase Unity SDK
var firebaseWorkaround = new AndroidJavaClass("FirebaseMessagingWorkaround");
firebaseWorkaround.CallStatic("subscribeAsync", topicName);
firebaseWorkaround.CallStatic("unsubscribeAsync", topicName);

Assets/Plugins/Android/FirebaseWorkaround.java

import android.util.Log;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;

public class FirebaseMessagingWorkaround
{
    public static void subscribeAsync(String topic)
    {
        FirebaseMessaging.getInstance().subscribeToTopic(topic)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    String msg;
                    if (task.isSuccessful())
                    {
                        msg = topic + " Subscribed";
                    }
                    else
                    {
                        msg = topic + " Unsubscribe failed";
                    }
                    Log.d("FirebaseWorkaround", msg);
                }
            });
    }

    public static void unsubscribeAsync(String topic)
    {
        FirebaseMessaging.getInstance().unsubscribeFromTopic(topic)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    String msg;
                    if (task.isSuccessful())
                    {
                        msg = topic + " Unsubscribed";
                    }
                    else
                    {
                        msg = topic + " Unsubscribe failed";
                    }
                    Log.d("FirebaseWorkaround", msg);
                }
            });
    }
}

Of course, you can also call subscribeToTopic()/unsubscribeFromTopic() with only AndroidJavaClass/AndroidJavaObject without preparing the above java file.

ModischFabrications commented 1 year ago

For anyone still looking: Don't bother updating yet, FCM v10.2.0 seems to have the same problem.

hippogamesunity commented 1 year ago

Right, they don't want to fix it, so GetTokenAsync() is the only solution at the moment.

Decavoid commented 1 year ago

FCM v10.3.0. TokenReceived is called only on the first launch. MessageReceived is never called.

visuallization commented 1 year ago

Experiencing the same problem! Any news on that issue? It is super annoying that this still hasn't been fixed but is still the recommended way to do things in the docs. I would suggest to either fix this or update the docs.

Nyankoo commented 1 year ago

@paulinon Pinging you to get this some attention. This issue is almost 2 years old now!