FirebaseInstanceIdService is deprecated and OnNewToken() not working

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.

Answers

  • jezhjezh Member, Xamarin Team Xamurai

    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.

  • borge_rodsjoborge_rodsjo NOMember ✭✭

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

    <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:

    <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

  • SagarPanwalaSagarPanwala USMember ✭✭✭

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

  • GautamJainGautamJain INMember ✭✭✭

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

  • DooksDooks ZAMember ✭✭✭

    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>
    
  • DeepfreezedDeepfreezed Member ✭✭
    edited August 2

    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.

  • SamPollockSamPollock GBMember ✭✭

    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();
            }
    
  • SamPollockSamPollock GBMember ✭✭

    PS I don't have proguard enabled

  • SamPollockSamPollock GBMember ✭✭

    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 :-)

  • 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 ?

Sign In or Register to comment.