我有一个 Xamarin Android 应用程序,我需要获取 Firebase 云消息传递令牌。
我在我的 Android 项目中添加了一个包含以下类的文件:
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseIIDService : FirebaseMessagingService
{
const string TAG = "MyFirebaseMsgService";
public override void OnNewToken(string token)
{
base.OnNewToken(token); // << Breakpoint here
SendRegistrationToServer(token);
}
public void SendRegistrationToServer(string token)
{
// Do something with the token
}
}
和我的 AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="13" android:versionName="13.1" package="com.MyApp.app" android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="18" android:targetSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<application android:label="MyApp" android:icon="@mipmap/launcher_foreground" android:hardwareAccelerated="true" android:debuggable="true">
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
</application>
</manifest>
我将应用程序部署到模拟设备,但从未到达断点。该应用程序已部署并正在运行。
我想知道这段代码是否足够,或者是否必须在其他地方引用该类。
我知道此代码仅在安装应用程序时运行一次。所以每次我都会卸载应用程序然后再次测试。
我该如何解决这个问题?
如果您想获取 Firebase Cloud Messaging Token,可以使用下面的代码。
var FCMtoken = FirebaseMessaging.Instance.GetToken().GetResult(Java.Lang.Class.FromType(typeof(InstallationTokenResult))).ToString();
此服务
MyFirebaseIIDService
实现了 OnTokenRefresh 方法,该方法在最初创建或更改注册令牌时调用。
OnTokenRefresh
很少被调用:用于在以下情况下更新令牌:
安装或卸载应用程序时。
当用户删除应用程序数据时。
当应用程序删除实例 ID 时。
当代币的安全性受到损害时。
您可以查看 MS 文档以获取更多详细信息。 https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=windows#implement-the-firebase-instance-id-service