Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android Firebase 8.0.0 TokenReceived called only on application reinstall #1088

Closed
maniaks1 opened this issue Jul 6, 2021 · 57 comments
Closed
Assignees
Milestone

Comments

@maniaks1
Copy link

maniaks1 commented Jul 6, 2021

[REQUIRED] Please fill in the following fields:

  • Unity editor version: 2018.4.31f1
  • Firebase Unity SDK version: 8.0.0
  • Source you installed the SDK: .unitypackage
  • Problematic Firebase Component: Messaging
  • Other Firebase Components in use: Analytics
  • Additional SDKs you are using: Google Play, Adjust, Appmetrica, DevToDev, Ironsource ad mediation( mediation networks Ironsource, UnityAds, Admob, Facebook, AdColony)
  • Platform you are using the Unity editor on: Mac 11.4
  • Platform you are targeting: iOS, Android
  • Scripting Runtime: IL2CPP

[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 paulinon removed the new New issue. label Jul 6, 2021
@paulinon
Copy link
Contributor

paulinon commented Jul 7, 2021

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?

@paulinon paulinon added the needs-info Need information for the developer label Jul 7, 2021
@maniaks1
Copy link
Author

maniaks1 commented Jul 8, 2021

Hi @paulinon!

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

  • Download test project
  • Add analytics and messaging from firebase sdk 8.0.0 (dotnet 4).
  • Add ExternalDependencyManager 1.2.166.
  • Run Android Resolver -> Force resolve.
  • Add google-services.json

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

@google-oss-bot google-oss-bot added needs-attention Need Googler's attention and removed needs-info Need information for the developer labels Jul 8, 2021
@paulinon paulinon added type: bug and removed type: question needs-attention Need Googler's attention labels Jul 8, 2021
@OrionDev23
Copy link

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
Copy link
Contributor

chkuang-g commented Jul 23, 2021

@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
Copy link
Contributor

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

@timoberquelle
Copy link

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.

  • Clean install a new app
  • Subscribing / unsubscribing works as intended
  • Kill app and restart
  • Subscribing / unsubscribing is not working anymore
  • Delete token
  • Get token
  • All previous attempts to subscribe / unsubscribe are now processed (all subscribing events before unsubscribing though, no matter the initial order)
  • Subscribing / unsubscribing works as intended again (until next app start)

@nostek
Copy link

nostek commented Sep 6, 2021

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
Copy link

Nyankoo commented Sep 26, 2021

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
Copy link

hippogamesunity commented Oct 2, 2021

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
Copy link

hippogamesunity commented Oct 2, 2021

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

@OrionDev23
Copy link

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
Copy link

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 cynthiajoan added this to the 8.3.0 milestone Oct 4, 2021
@cynthiajoan
Copy link
Contributor

Fixed in release 8.3.0

@Nyankoo
Copy link

Nyankoo commented Oct 7, 2021

@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!

@Nyankoo
Copy link

Nyankoo commented Jun 7, 2022

@paulinon Any update?

@BielBG
Copy link

BielBG commented Jun 27, 2022

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
Copy link

BielBG commented Jun 27, 2022

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
Copy link

AOEGame commented Jul 18, 2022

same problem in 9.1.0 and 9.2.0

@AOEGame
Copy link

AOEGame commented Jul 19, 2022

anyone fixed this problem?? any workaround?

@AOEGame
Copy link

AOEGame commented Jul 19, 2022

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
Copy link

AOEGame commented Jul 19, 2022

@Guidanel
9.1.0 9.2.0 also has this problem.

do you find any workarounds?

@Seanm07
Copy link

Seanm07 commented Jul 19, 2022

@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
Copy link

AOEGame commented Jul 19, 2022

@Seanm07

Thank you very much for your answer!

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

@Seanm07
Copy link

Seanm07 commented Jul 19, 2022

@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
Copy link

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
Copy link

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
Copy link

XaviSMP commented Aug 22, 2022

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
Copy link

Gnejs commented Oct 5, 2022

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
Copy link

Seanm07 commented Oct 5, 2022

@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
Copy link

Another workaround:

  • Instead of TokenReceived, use GetTokenAsync().
  • Instead of SubscribeAsync()/UnsubscribeAsync(), use subscribeToTopic()/unsubscribeFromTopic() of Firebase Android SDK.
// 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
Copy link

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

@hippogamesunity
Copy link

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

@Decavoid
Copy link

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

@visuallization
Copy link

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
Copy link

Nyankoo commented Apr 3, 2023

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

@habitoti
Copy link

Is Firebase even maintained still? Just updated from my old 7.2 Firebase version to 10.7 to try some of the latest desktop support beta stuff, just to find that this crucial feature is broken since ages. That's ridiculous...

@TaejunPark
Copy link

This is still happening on 11.6.0
I updated to the new version. I thought it sure is fixed as it was about 2 years ago and commented old dirty codes, but just not working 😇
I already spent another days to fix unity firebase-android plugin problem before this, and last week update just gone.

fb team all looking happy on youtube
enjoying making their shit(= firebase for unity) long(=version ups for what?), like my AR book🤤

@Nyankoo
Copy link

Nyankoo commented Oct 30, 2023

@paulinon @chkuang-g @cynthiajoan A statement would be nice. It's unbelievable that this is still not fixed!

@lsw1164
Copy link

lsw1164 commented Oct 30, 2023

Still not working...? I can't wait to work it.

@FrantisekHolubec
Copy link

FrantisekHolubec commented Apr 11, 2024

Still problem on 11.9.0.
anybody has some workaround for android and ios?

@Gnejs
Copy link

Gnejs commented Jul 15, 2024

So here we are again, almost two years since I last commented, SDK 12.1.0 and this is still an issue.

To re-iterate, just calling GetTokenAsync() will not work, since it will only give you the token, the SDK is still broken and subscribing will NOT actually work.

Good news though, I did try the workaround suggested by [homu-konamilk] #1088 (comment)
and I can confirm that getting the token AND using the native java wrapper class does in fact work.
This workaround seems much better than deleting the token and re-subscribing to all topics.

Makes you wonder how many Unity Android Apps have broken firebase integrations out there when everything seems fine first launch.

Anyway, hopefully someone finds this useful, try the aforementioned workaround. :)

@a-maurice
Copy link
Contributor

The latest release should finally fix this, 12.3.0, https://github.com/firebase/firebase-unity-sdk/releases/tag/v12.3.0

Thanks for raising this, and sorry it took so long to fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests