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

Xamarin.Forms安卓端因iOS通知代码崩溃问题求助

解决Xamarin.Forms中Android端因iOS通知代码引发的程序集加载错误

问题核心在于:Device.RuntimePlatform是运行时判断,编译阶段Android项目仍会包含对Xamarin.iOS程序集的引用,导致运行时Android系统尝试加载不存在的程序集,抛出FileNotFoundException。以下是可行的解决方案:

方案1:使用条件编译符号隔离iOS代码

直接通过编译符号让Android编译时完全忽略iOS专属代码,从根源避免程序集引用问题。Xamarin默认给各平台定义了专属编译符号:iOS是__IOS__,Android是__ANDROID__。

修改代码为:

#if __IOS__
    UNUserNotificationCenter.Current.RemovePendingNotificationRequests(requests);
#endif

这样编译Android项目时,这段iOS代码会被直接排除,不会产生任何Xamarin.iOS程序集的依赖。

方案2:通过依赖服务实现平台专属逻辑

将通知操作抽象为接口,各平台分别实现,彻底隔离平台代码:

  1. 定义共享接口:
public interface INotificationManager
{
    void RemovePendingNotifications(string[] requestIds);
}
  1. iOS端实现:
[assembly: Dependency(typeof(IOSNotificationManager))]
namespace YourAppNamespace.iOS
{
    public class IOSNotificationManager : INotificationManager
    {
        public void RemovePendingNotifications(string[] requestIds)
        {
            UNUserNotificationCenter.Current.RemovePendingNotificationRequests(requestIds);
        }
    }
}
  1. Android端实现(对应Android通知移除逻辑):
[assembly: Dependency(typeof(AndroidNotificationManager))]
namespace YourAppNamespace.Droid
{
    public class AndroidNotificationManager : INotificationManager
    {
        public void RemovePendingNotifications(string[] requestIds)
        {
            // 实现Android移除待发送通知的逻辑
            var notificationManager = NotificationManagerCompat.From(Android.App.Application.Context);
            foreach(var id in requestIds)
            {
                if(int.TryParse(id, out var notificationId))
                {
                    notificationManager.Cancel(notificationId);
                }
            }
        }
    }
}
  1. 共享代码中调用:
DependencyService.Get<INotificationManager>().RemovePendingNotifications(requests);

方案3:检查并清理项目引用

  • 打开Android项目的引用列表,确认没有引用Xamarin.iOS程序集,若存在则直接移除。
  • 手动删除Android项目的bin和obj目录,然后执行清理解决方案+重新生成操作,确保残留的编译文件被完全清除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:05:34