0

i am trying to create a messaging app using xamarin.forms and fcm. i am trying to create a token for each user upon login. i am using the same device to login to each user. the thing is that same token is being genberated. this is my code:

in xamarin.android project in MainActivity.cs:

  public static FirebaseApp app ;
        
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            string userid = Preferences.Get("userid", "");
            FirebaseOptions options = new FirebaseOptions.Builder().SetApplicationId("my_app_id").SetApiKey("my_api_key").SetProjectId("my_project_id").Build();
            app = FirebaseApp.InitializeApp(this, options, "User" + userid);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

and this is my getToken class

using Android.App;
using Android.Content;
using Android.Gms.Extensions;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Firebase.Iid;
using LearningWithCassidy;
using LearningWithCassidy.Droid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

[assembly: Xamarin.Forms.Dependency(typeof(GetTokenAndroid))]
namespace LearningWithCassidy.Droid
{
    internal class GetTokenAndroid:GetToken
    {
        public async Task<string> get_token()
        {

            FirebaseInstanceId firebaseInstanceId = FirebaseInstanceId.GetInstance(MainActivity.app);
            var instanceIdResult = await firebaseInstanceId.GetInstanceId().AsAsync<IInstanceIdResult>();
            var token = instanceIdResult.Token;
            return token;


        }
    }
}

and this is how i get the token in my MainPage.xaml.cs

string token="";
 token = await DependencyService.Get<GetToken>().get_token();
                                System.Diagnostics.Debug.WriteLine($"Token: {token}");

what am i doing wrong? why do i keep getting the same token?

thanks in advance

rana hd
  • 355
  • 3
  • 18
  • Does this help: [Managing Firebase Cloud Messaging Tokens with Multiple Users](https://stackoverflow.com/questions/67767014/managing-firebase-cloud-messaging-tokens-with-multiple-users) – Liqun Shen-MSFT Feb 14 '23 at 09:13

1 Answers1

0

You have to delete the current token using deleteToken() whenever a user logs out. This will invalidate the token of the old user. Then, generate a new one after a new user logs in.

Yuji Bry
  • 304
  • 8