locked
FirebaseInstanceIdService is deprecated and OnNewToken() not working RRS feed

  • Question

  • User368472 posted

    I want to implement OnNewToken() method from FirebaseMessagingService in my Xamarin Android project that uses Firebase Cloud Messaging since FirebaseInstanceIdService and OnTokenRefreshed() are deprecated.

    I tried this

    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class MessagingService : FirebaseMessagingService
    {
        const string TAG = "MyFirebaseMsgService";
        public override void OnNewToken(string token)
        {
            Log.Debug(TAG, "Refreshed token: " + token);
            SendRegistrationToServer(token);
        }
    
        public void SendRegistrationToServer(string token)
        {
            ...
        }
    
    }
    

    But my OnNewToken() is not hit. What am I doing wroing. Do i need to include anything in my Android manifest file? I cannot find any documents specific to Xamarin Android about this update. Please help. Thank you so much.

    Sunday, August 19, 2018 3:40 AM

All replies

  • User371688 posted

    The onNewToken method will only be called when a new token is generated. Quite often (especially during development) your app already have generated a token before you added the service. So onNewToken will not be called. If you want to get the token directly , the class FirebaseInstanceId may be helpful.

    Monday, August 20, 2018 7:49 AM
  • User116858 posted

    @prabesh I have the same code as you, and I have the same problem; OnNewToken(string token) is not being called. I'm using all of the newest packages like:

    xml <package id="Xamarin.Firebase.Iid" version="70.1620.0-preview2" targetFramework="monoandroid90" /> <package id="Xamarin.Firebase.Messaging" version="70.1710.0-preview2" targetFramework="monoandroid90" /> <package id="Xamarin.Firebase.Config" version="70.1600.0-preview2" targetFramework="monoandroid90" />

    In my manifest I have this:

    xml <receiver android:exported="false" android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"/> <receiver android:exported="true" android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:permission="com.google.android.c2dm.permission.SEND"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE"/> <action android:name="com.google.android.c2dm.intent.REGISTRATION"/> <category android:name="${applicationId}"/> </intent-filter> </receiver>

    Please, someone, look into the new way of getting FCM token

    Thursday, November 22, 2018 9:07 PM
  • User75709 posted

    @borge_rodsjo I personally didn't try , but this can be useful. https://forums.xamarin.com/discussion/136721/firebaseinstanceidservice-is-deprecated-and-onnewtoken-not-working

    If you try , please let us know the feedback.

    Saturday, December 22, 2018 10:21 AM
  • User40225 posted

    Fixed in latest Xamarin.Firebase.Messaging (still in preview) - Version 70.1710.0-preview2

    Wednesday, February 6, 2019 9:21 AM
  • User237535 posted

    It is now May 2019. Did you figure it out @prabesh

    I'm getting the following error:

    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.internal.firebase-perf.zzq.zzb(boolean)' on a null object reference
    

    I have tried adding the following to the Manifest:

    <service android:name="com.google.firebase.components.ComponentDiscoveryService" >
      <meta-data android:name="com.google.firebase.components:com.google.firebase.iid.Registrar" android:value="com.google.firebase.components.ComponentRegistrar" />
    </service>
    
    Monday, May 27, 2019 3:12 PM
  • User387959 posted

    Got this working...

    Add below to AndroidManifest.xml <service android:name=".MyFirebaseMessagingService" android:stopWithTask="false"><intent-filter><action android:name="com.google.firebase.MESSAGING_EVENT" /></intent-filter></service>

    Rest of the code same as OP.

    Friday, August 2, 2019 7:46 PM
  • User12471 posted

    Hi All, really struggling to get this working. I have been away from Xamarin for 18 months and gone native but due to a client requesting Xamarin I am back here.

    I have similar code working in a native java app but I am struggling with this.

    I have the above code in my manifest but I am getting the following

    Java.Lang.RuntimeException: Unable to instantiate service .MyFirebaseMessagingService: java.lang.ClassNotFoundException: Didn't find class "packagename.MyFirebaseMessagingService" on path: DexPathList

    [Service]
        [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
        public class MyFirebaseMessagingService : FirebaseMessagingService
        {
            const string TAG = "MyFireBaseMessagingService";
    
            public override void OnNewToken(string token)
            {
                Log.Debug(TAG, "Refreshed token: " + token);
                SendRegistrationToServer(token);
            }
    
    
            public override void OnMessageReceived(RemoteMessage message)
            {
                Log.Debug(TAG, "From: " + message.From);
    
                var body = message.GetNotification().Body;
                Log.Debug(TAG, "Notification Message Body: " + body);
                SendNotification(body, message.Data);
            }
    
            void SendNotification(string messageBody, IDictionary<string, string> data)
            {
                var intent = new Intent(this, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop);
                foreach (var key in data.Keys)
                {
                    intent.PutExtra(key, data[key]);
                }
    
                var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot);
    
                var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                                          //.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
                                          .SetContentTitle("FCM Message")
                                          .SetContentText(messageBody)
                                          .SetAutoCancel(true)
                                          .SetContentIntent(pendingIntent);
    
                var notificationManager = NotificationManagerCompat.From(this);
                notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
            }
    
            void SendRegistrationToServer(string token)
            {
                // Add custom implementation, as needed.
                ISharedPreferences prefs;
                ISharedPreferencesEditor prefseditor;
                prefs = PreferenceManager.GetDefaultSharedPreferences(this);
                prefseditor = prefs.Edit();
    
                prefseditor.PutBoolean(Constants.PREFS_FCM_TOKEN_CHANGED, true);
                prefseditor.PutString(Constants.PREFS_FCM_TOKEN, token);
    
                if (prefs.GetString(Constants.PREFS_DEVICE_GUID, "") == "")
                {
                    prefseditor.PutString(Constants.PREFS_DEVICE_GUID, Guid.NewGuid().ToString().Replace(" ", "").ToLower());
                }
    
                prefseditor.Commit();
            }
    
    Friday, August 16, 2019 6:28 AM
  • User12471 posted

    PS I don't have proguard enabled

    Friday, August 16, 2019 6:36 AM
  • User12471 posted

    Ok guys, in case it helps anyone else, I have this working now. I needed to add this to the top of my service

    [Service (Name= "packagename.MyFirebaseMessagingService")]

    it now fires the onNewtoken and finds the service

    Onwards and Upwards :-)

    Friday, August 16, 2019 7:00 AM
  • User281549 posted

    Im using Xamarin.Firebase.Messaging version 60.1142.1 and it is erroring saying that FirebaseInstanceIdService is deprecated and at runtime we are getting the unsuccessful registration for firebase error, even after cleaning and rebuilding the android project. Is there going to be a fix for Xamarin.Firebase.Messaging version 60.1142.1 ?

    Monday, September 16, 2019 9:28 PM
  • User184959 posted

    @SamPollock said: Ok guys, in case it helps anyone else, I have this working now. I needed to add this to the top of my service

    [Service (Name= "packagename.MyFirebaseMessagingService")]

    it now fires the onNewtoken and finds the service

    Onwards and Upwards :-)

    @SamPollock can you show us your android manifest?

    Wednesday, October 23, 2019 11:35 AM
  • User12471 posted

    I cant really show the manifest however the relevant part is

    <service android:name="com.yourpackagename.MyFirebaseMessagingService" android:stopWithTask="false">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT" />
                </intent-filter>
            </service>
    
    Wednesday, October 23, 2019 11:39 AM
  • User390410 posted

    @SamPollock said: Ok guys, in case it helps anyone else, I have this working now. I needed to add this to the top of my service

    [Service (Name= "packagename.MyFirebaseMessagingService")]

    it now fires the onNewtoken and finds the service

    Onwards and Upwards :-)

    God bless you, Sam! You saved my day! My resulting file (MyFirebaseMessagingService.cs) looks like:

    using System;
    using Android.App;
    using Firebase.Messaging;
    using Android.Util;
    
    namespace <PASTE_YOUR_APP_NAME_HERE>
    {
        [Service(Name = "<PASTE_YOUR_PACKAGE_NAME_HERE>.MyFirebaseMessagingService")]
        [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
        public class MyFirebaseMessagingService : FirebaseMessagingService
        {
    
            public override void OnNewToken(string token)
            {
                base.OnNewToken(token);
            }
    
            public override void OnMessageReceived(RemoteMessage remoteMessage)
            {
                base.OnMessageReceived(remoteMessage);
            }
        }
    }
    
    Friday, November 22, 2019 11:33 AM
  • User392495 posted

    @jezh said: The onNewToken method will only be called when a new token is generated. Quite often (especially during development) your app already have generated a token before you added the service. So onNewToken will not be called. If you want to get the token directly , the class FirebaseInstanceId may be helpful.

    This is correct - onNewToken() will be called only once per installation. If you need it to be called again, uninstall the app from your device and restart it.

    Thursday, January 30, 2020 5:09 AM
  • User393839 posted

    I found this up to date documentation made by Microsoft: docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm#set-up-notification-hubs-in-your-project (sorry about the broken link, this forum doesn't allow to insert link when you are new)

    Thursday, April 9, 2020 11:00 AM
  • User207892 posted

    @SamPollock We are facing the same issue where OnNewToken method never hits , I have tried all the possible ways mentioned above, and when i try this FirebaseMessaging.Instance.AutoInitEnabled = true; The below error is thrown at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in :0 at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in :0 at Firebase.Messaging.FirebaseMessaging.setAutoInitEnabled (System.Boolean value) [0x00022] in <950f147afc11488abae5c0be3de4f06e>:0 at AspenConnect.Droid.MainActivity.OnCreate (Android.OS.Bundle savedInstanceState) [0x00130] in /Users/733728/Documents/GitHub/AspenConnect/AspenConnect/AspenConnect.Android/MainActivity.cs:96 --- End of managed Java.Lang.NullPointerException stack trace --- java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.firebase.iid.FirebaseInstanceId.zzb(boolean)' on a null object reference at com.google.firebase.messaging.FirebaseMessaging.setAutoInitEnabled(Unknown Source:8) at crc64c42fb79c8c2d6d3a.MainActivity.nonCreate(Native Method) at crc64c42fb79c8c2d6d3a.MainActivity.onCreate(MainActivity.java:33) at android.app.Activity.performCreate(Activity.java:7224) at android.app.Activity.performCreate(Activity.java:7213) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:201) at android.app.ActivityThread.main(ActivityThread.java:6810) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

    Wednesday, August 12, 2020 8:05 AM
  • User207892 posted

    @SamPollock We are facing the same issue where OnNewToken method never hits , I have tried all the possible ways mentioned above, and when i try this FirebaseMessaging.Instance.AutoInitEnabled = true; The below error is thrown:java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.firebase.iid.FirebaseInstanceId.zzb(boolean)' on a null object reference at com.google.firebase.messaging.FirebaseMessaging.setAutoInitEnabled(Unknown Source:8)

    Wednesday, August 12, 2020 8:05 AM
  • User12471 posted

    @Kanth said: @SamPollock We are facing the same issue where OnNewToken method never hits , I have tried all the possible ways mentioned above, and when i try this FirebaseMessaging.Instance.AutoInitEnabled = true; The below error is thrown:java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.firebase.iid.FirebaseInstanceId.zzb(boolean)' on a null object reference at com.google.firebase.messaging.FirebaseMessaging.setAutoInitEnabled(Unknown Source:8)

    Apologies Kanth, I cant really look into this at the moment, I am not currently doing much Xamarin as have moved mainly native although still have a few projects on the go, if anything springs to mind when I get back to them in a few weeks I will post here.

    Wednesday, August 12, 2020 8:49 AM
  • User207892 posted

    Including the Xamarin.Android.ManifestMerger solved this issue for me: https://www.nuget.org/packages/Xamarin.Android.ManifestMerger/1.0.0-preview03

    Using this fixed by issue

    Thursday, August 13, 2020 10:58 AM
  • User391162 posted

    After two days of troubleshooting, finally i found out that the latest versions of the below nuget packages (or may be one of them) is causing this. I downgraded to the below versions and it started working.

    Xamarin.Azure.NotificationHubs.Android -> v0.6.0
    Xamarin.Firebase.Messaging -> v71.1740.0
    Xamarin.GooglePlayServices.Base -> v71.1610.0
    
    Tuesday, December 1, 2020 9:16 AM