Forum Xamarin.Forms

FCM token for push notifications - FirebaseInstanceId.Intance.Token obsolete

JeremyBoutotJeremyBoutot Member ✭✭
edited August 2018 in Xamarin.Forms

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

Best Answer

Answers

  • JeremyBoutotJeremyBoutot Member ✭✭

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

  • AntonioStan.2954AntonioStan.2954 USMember ✭✭
    edited July 2019

    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();
  • NaidyuNaidyu Member

    How exaclty I can use token after OnSuccess?

  • AdrianoPetrucciAdrianoPetrucci USMember ✭✭

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

  • AdrianoPetrucciAdrianoPetrucci USMember ✭✭

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

    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)
    {
        ...
    }
    ........
    }
    
  • johanfranzenjohanfranzen SEUniversity
    edited October 2019

    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)

  • ramarama GBMember ✭✭
    edited April 11

    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<IPushNotificationsHelper>();
    
                        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);
    
Sign In or Register to comment.