You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Forms适配Android 12遇PendingIntent运行时异常求助

解决Xamarin Forms应用Android 12运行时PendingIntent异常问题

问题根源

Android 12(API级别31)开始,创建PendingIntent时必须显式指定FLAG_IMMUTABLE或FLAG_MUTABLE标记,否则会触发运行时异常。你的崩溃日志显示问题来自旧版Firebase IID库,它未适配这个新要求。

修复步骤

  • 升级Firebase相关NuGet包
    旧版Firebase IID已被Firebase Messaging取代,新版本已适配Android 12的PendingIntent规则。将项目中以下NuGet包升级到最新稳定版:

    • Xamarin.Firebase.Messaging
    • Xamarin.GooglePlayServices.Base(若有依赖)

    注意:Firebase IID已被弃用,建议迁移到Firebase Messaging获取推送令牌。

  • 替换Firebase IID代码为Firebase Messaging
    把旧的FirebaseInstanceId.GetToken()调用替换为Firebase Messaging的API:

    // 旧代码(Firebase IID)
    var token = FirebaseInstanceId.Instance.GetToken();
    
    // 新代码(Firebase Messaging)
    var token = await FirebaseMessaging.Instance.GetTokenAsync();
    
  • 设置Android项目目标SDK为31或更高
    在Android项目属性中,将目标框架设置为Android 12(API 31)及以上,同步更新编译SDK版本。

  • 兼容旧库的临时处理(可选)
    若暂时无法升级库,可自定义FirebaseInstanceIdService子类,手动添加PendingIntent标记:

    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseInstanceIdService : FirebaseInstanceIdService
    {
        public override void OnTokenRefresh()
        {
            var refreshedToken = FirebaseInstanceId.Instance.Token;
            // 令牌处理逻辑
    
            // 适配Android 12的PendingIntent标记
            var intent = new Intent(this, typeof(MyFirebaseMessagingService));
            var flags = Build.VERSION.SdkInt >= BuildVersionCodes.S 
                ? PendingIntentFlags.Immutable 
                : PendingIntentFlags.UpdateCurrent;
            var pendingIntent = PendingIntent.GetService(this, 0, intent, flags);
            // 后续pendingIntent使用逻辑
        }
    }
    

验证

将应用部署到Android 12设备,检查是否仍出现该运行时异常,同时确认推送令牌可正常获取。

内容的提问来源于stack exchange,提问作者neha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 12:39:51