xamarin 未调用FCM OnTokenRefresh()方法

7fyelxc5  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(114)

我试图从FCM获取设备令牌。此代码在演示项目中工作,但当我尝试在我的项目中使用它时,OnTokenRefresh方法未被调用。我完美地完成了所有设置,但我不知道为什么方法未被调用。
谢谢大家。

FirebaseInstanceIDService.cs

[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
[System.Obsolete]
public class FirebaseInstanceIDService : FirebaseInstanceIdService
{
    const string TAG = "MyFirebaseIIDService";

    // [START refresh_token]
    [System.Obsolete]
    public override void OnTokenRefresh()
    {
        // Get updated InstanceID token.
        var refreshedToken = FirebaseInstanceId.Instance.Token;
        Android.Util.Log.Debug(TAG, "Refreshed token: " + refreshedToken);
        System.Diagnostics.Debug.WriteLine($"######Token######  :  {refreshedToken}");
       
        Xamarin.Forms.Application.Current.Properties["Fcmtocken"] = FirebaseInstanceId.Instance.Token ?? "";
        Xamarin.Forms.Application.Current.SavePropertiesAsync();
    }
    // [END refresh_token]
}

MainActivity.cs

protected override void OnCreate(Bundle savedInstanceState)
{
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;
   
    base.Window.RequestFeature(WindowFeatures.ActionBar);
    CrossCurrentActivity.Current.Init(this, savedInstanceState);
    base.OnCreate(savedInstanceState);

    
    Xamarin.Essentials.Platform.Init(this, savedInstanceState);

    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    NotificationCenter.CreateNotificationChannel(new NotificationChannelRequest());
    Xamarin.FormsMaps.Init(this, savedInstanceState);
    ZXing.Net.Mobile.Forms.Android.Platform.Init();
    
    FirebaseApp.InitializeApp(this);
    
    LoadApplication(new App());
    NotificationCenter.NotifyNotificationTapped(Intent);           
}
mxg2im7a

mxg2im7a1#

你现在做的已经过时了。
对于启动场景,你应该在某处实现一个Android.Gms.Tasks.IOnSuccessListener,并像这样注册这个监听器:

FirebaseApp.InitializeApp(context);
FirebaseMessaging.Instance.GetToken().AddOnSuccessListener(<your listener instance here>);

然后将FirebaseInstanceIdService更改为FirebaseMessagingService:

[Service(Exported = false)]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public sealed class MyMessagingService : FirebaseMessagingService
{
    public override void OnMessageReceived(RemoteMessage message)
    {
        // you got a notification
    }

    public override void OnNewToken(string token)
    {
        // you got a new token
    }
}

相关问题