Xamarin转MAUI重用Firebase.Messaging部署时遇JNI Handle激活异常
遇到的错误:
System.NotSupportedException: 'Could not activate JNI Handle 0x7ff89520c0 (key_handle 0x41b7022) of Java type 'crc64b0d4ce38c317adf3/NotificationService' as managed type 'ZipExtractMaui.Droid.NotificationService'.'
核心原因
该错误源于Xamarin.Firebase.Messaging生成的Java代理类(以crc64开头)与MAUI项目中NotificationService的类型签名不匹配,或是MAUI与Xamarin的绑定机制差异导致类型映射失败。
解决方案
1. 校验NotificationService类的定义
确保你的ZipExtractMaui.Droid.NotificationService满足以下要求:
- 必须为public访问修饰符
- 正确继承
FirebaseMessagingService - 标注正确的特性:
[Service] [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })] public class NotificationService : FirebaseMessagingService { // 重写OnMessageReceived、NewToken等必要方法 public override void OnMessageReceived(RemoteMessage message) { // 处理消息逻辑 } }
2. 清理重建项目
- 删除MAUI项目的
bin、obj目录,同时清除Android缓存目录%USERPROFILE%\AppData\Local\Xamarin下的相关文件 - 先单独生成Android项目,再进行部署操作
3. 替换为MAUI兼容的Firebase包
Xamarin.Firebase.Messaging并非为MAUI设计,长期来看建议替换为.NET MAUI官方适配的Firebase库(如Firebase.Messaging)。若需临时复用,确保Xamarin.Firebase.Messaging更新至最新兼容版本,避免版本冲突。
4. 配置ProGuard规则(若启用)
如果项目开启了ProGuard混淆,需在ProGuard.cfg中添加规则保护相关类不被混淆:
-keep class com.google.firebase.** { *; } -keep class ZipExtractMaui.Droid.NotificationService { *; } -keep class crc64b0d4ce38c317adf3.NotificationService { *; }
5. 验证AndroidManifest配置
确认AndroidManifest.xml中正确注册了服务(MAUI通常会自动根据特性生成,可手动核对):
<service android:name="ZipExtractMaui.Droid.NotificationService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
同时确保google-services.json已放置在Android项目的Resources目录,且Build Action设置为GoogleServicesJson。
内容的提问来源于stack exchange,提问作者Micheal Patrick

