locked
FCM token for push notifications - FirebaseInstanceId.Intance.Token obsolete RRS feed

  • Question

  • User372431 posted

    Hey everyone. All the examples I see for getting the FCM token in Xamarin use FirebaseInstanceIdService which gives a warning it is is depreciated and obsolete. The code snippet below is an example how I can get the FCM token, but since this is depreciated, what is the recommended way?

                public class MyFirebaseIIDService : FirebaseInstanceIdService
                {
                    public override void OnTokenRefresh()
                    {
                        var refreshedToken = FirebaseInstanceId.Instance.Token;
                    }
    
                }
    

    I have seen android specific code in Java that looks similar to this as the "new way", but I can't seem to translate this into Xamarin.

    FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this,  new OnSuccessListener<InstanceIdResult>() {
         @Override
         public void onSuccess(InstanceIdResult instanceIdResult) {
               String newToken = instanceIdResult.getToken();
               Log.e("newToken",newToken);
    
         }
     });
    

    Any suggestions or are people just continuing to use the depreciated method in Xamarin? Thanks!

    Jeremy

    Thursday, August 16, 2018 6:24 PM

Answers

  • User371688 posted

    @JeremyBoutot The alternative method to get the FCM token in Xamarin has include in the newest version of Xamarin.Firebase.Messaging Nuget (70.1710.0-preview2). But it's the Preview version, so it's maybe not very stable.

    class TestService: FirebaseMessagingService
    {
        public override void OnNewToken(string p0)
        {
            base.OnNewToken(p0);
        }
    }
    
    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, August 17, 2018 9:51 AM

All replies

  • User371688 posted

    @JeremyBoutot The alternative method to get the FCM token in Xamarin has include in the newest version of Xamarin.Firebase.Messaging Nuget (70.1710.0-preview2). But it's the Preview version, so it's maybe not very stable.

    class TestService: FirebaseMessagingService
    {
        public override void OnNewToken(string p0)
        {
            base.OnNewToken(p0);
        }
    }
    
    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, August 17, 2018 9:51 AM
  • User372431 posted

    @jezh Thank you that gave me the new token as it was assigned.

    Friday, August 17, 2018 12:56 PM
  • User216075 posted

    As "FirebaseInstanceId.Instance.Token" became obsolete, for getting the token you can use the following: 1. Implement in your class Android.Gms.Tasks.IOnSuccessListener - if you also extend Java.Lang.Object, you can remove the Dispose() and Handle{get;}

    public class MyActivity : AppCompatActivity, Android.Gms.Tasks.IOnSuccessListener
    {
        protected override void OnCreate(Android.OS.Bundle bundle)
        {
            ...
            FirebaseInstanceId.Instance.GetInstanceId().AddOnSuccessListener(this);
            ...
        }
    
        public void OnSuccess(Java.Lang.Object result)
        {
                var token = result.Class.GetMethod("getToken").Invoke(result).ToString();
        }
    }
    
    1. Call FirebaseInstanceId.Instance.GetInstanceId().AddOnSuccessListener(this);
    2. Apply reflection in OnSuccessMethod(Java.Lang.Object result) var token = result.Class.GetMethod("getToken").Invoke(result).ToString();
    Tuesday, July 23, 2019 10:36 AM
  • User389192 posted

    How exaclty I can use token after OnSuccess?

    Friday, September 20, 2019 2:50 PM
  • User283907 posted

    @"AntonioStan.2954" said: As "FirebaseInstanceId.Instance.Token" became obsolete, for getting the token you can use the following: 1. Implement in your class Android.Gms.Tasks.IOnSuccessListener - if you also extend Java.Lang.Object, you can remove the Dispose() and Handle{get;}

      public void OnSuccess(Java.Lang.Object result)
        {
                var token = result.Class.GetMethod("getToken").Invoke(result).ToString();
        }
    }
    

    It works perfectly. But does it just ignore or bypass a warning? getToken is obsolete, like FirebaseInstanceId.Instance.Token.

    https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId#public-string-gettoken-

    So, even calling getToken could be a problem, right?

    Wednesday, October 30, 2019 2:40 PM
  • User283907 posted

    I found another way (but since this is not documented, probably it is just luck and it doesnt' work :P).

    Anyway, the problem is that OnNewToken is not called on each app start and sometimes you loose the token and want to know what the token is at the moment.

    Can't understand why Google have to obsolete everything they write, after a fews months... Why?

    But on the documentation, you can find this:

    public String getToken (String senderId, String scope)

    At this point it is easy! Just port it to Xamarin, use the c# format and... Wait!?!? sender Id? Scope?

    I don't know if it is correct, but it works, so please write me if it is not correct.

    The sender ID is the number in your google-services.json, for example in client-info->mobilesdkappid, on the string: 1:888888888:android:999999999999999, the sender id is 88888888888.

    Or you can find it in the dashboard, under settings cloud messaging: dashboard

    Now, you can put the code somewhere in your code. For example in the FirebaseService.cs (where you have also OnNewToken()). Maybe in a Init function, so you can retrieve this token at beginning.

    It can not run in the main thread, this will give you an exception, since the call need 1-2 seconds to be executed.

    So, you can write something like this: cpp public class FirebaseService : FirebaseMessagingService { public static String MyToken = ""; public static void Init(Activity activity) { Firebase.FirebaseApp.InitializeApp(activity); System.Threading.Tasks.Task.Run(() => { var testToken = FirebaseInstanceId.Instance.GetToken("888888888888", "GCM"); if(testToken != null) MyToken = testToken; }); } public override void OnNewToken(string newToken) { ... } ........ }

    Wednesday, October 30, 2019 3:44 PM
  • User73084 posted

    In case you lost your token and want to get it again, here is a different take on the solution by @AntonioStan.2954.

    var instanceId = await FirebaseInstanceId.Instance.GetInstanceId();
    var token = instanceId.Class.GetMethod("getToken").Invoke(instanceId).ToString();

    (getToken on the InstanceId object is not deprected)

    Thursday, October 31, 2019 3:00 PM
  • User200898 posted

    Posting this to help avoid using obsoleted API:

    To Request a token, you can create an Activity to handle the Android Promise like this:

    ``` using Android.App; using Android.Gms.Tasks; using Android.Util; using Firebase.Installations; using Xamarin.Forms;

    public class AppFirebaseMessagingRequestToken : Activity, IOnCompleteListener { public void OnComplete(Task task) { if (task?.Result != null) { var tokenResult = task.Result as InstallationTokenResult;

                if (tokenResult == null)
                {
                    return;
                }
    
                var token = tokenResult.Token;
    
                Log.Debug(nameof(AppFirebaseMessagingRequestToken), "Token: " + token);
    

    _// ** delete or change the code below to work and do something **** System.Threading.Tasks.Task.Run(async () => { var helper = DependencyService.Resolve();

                    await helper.SavePushNotificationTokenToLocalDbAsync(token);
    
                });
    

    // ** ********* **** _

            }
        }
    }
    

    ```

    Use the code below to actually request the token:

    ``` AppFirebaseMessagingRequestToken AppFirebaseMessagingRequestToken = new AppFirebaseMessagingRequestToken();

    var requestNewToken=false; // false get existing, true to force refresh

    FirebaseInstallations.Instance.GetToken(requestNewToken) .AddOnCompleteListener(AppFirebaseMessagingRequestToken); ```

    Sunday, April 11, 2021 12:47 PM