RazrMan
RazrMan

Reputation: 163

How to save Firebase Device Token in Xamarin.Forms Android

This is my code:

    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseIIDService : FirebaseInstanceIdService
    {
        public ISharedFunctions SharedFunctions => DependencyService.Get<ISharedFunctions>();
        const string TAG = "MyFirebaseIIDService";
        public override void OnTokenRefresh()
        {        
            var refreshedToken = FirebaseInstanceId.Instance.Token;
           
            Log.Debug(TAG, "Refreshed token: " + refreshedToken);
           
            SendRegistrationToServer(refreshedToken);
        }
        void SendRegistrationToServer(string token)
        {
            // Add custom implementation, as needed.
            SharedFunctions.SaveFirebaseDeviceToken(token);
            SharedFunctions.GetFirebaseDeviceToken();

        }
    }

But i get this error:

System.InvalidOperationException: 'You must call Xamarin.Forms.Forms.Init(); prior to using this property.'

How to save it with DependencyService , because i use same Shared Function for save and get the token in Android and IOS?

Upvotes: 0

Views: 520

Answers (1)

nevermore
nevermore

Reputation: 15786

You can't use DependencyService to send data from platform project to shared project.

I would recommend you to use MessagingCenter to send the data:

MessagingCenter.Send<MainPage>(this, "Hi");

And in shared project:

MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) =>
{
    // Do something whenever the "Hi" message is received
});

If you want to get/save some data in Xamarin.forms, you can use Xamarin.Essentials: Preferences :

Save the value with key:

Preferences.Set("my_key", "my_value");

Get the value with key:

var myValue = Preferences.Get("my_key", "default_value");

Upvotes: 1

Related Questions