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

订阅通知接口导致Xamarin Forms Android应用崩溃问题求助

问题根因

你遇到的空引用异常核心是 DependencyService.Get<INotificationManager>() 返回了null,触发原因如下:

  • 未在Android平台项目中实现INotificationManager接口
  • 实现类未注册到Xamarin.Forms依赖服务容器
  • 小概率是接口定义位置错误(放在了平台项目而非共享项目)
解决方案步骤

1. 补充缺失的公共类与平台实现

首先在共享项目中补充NotificationEventArgs类定义(你代码中用到了该类但未声明):

public class NotificationEventArgs : EventArgs
{
    public string Title { get; set; }
    public string Message { get; set; }
}

然后在Android平台项目中新建AndroidNotificationManager.cs类,实现接口并注册依赖服务:

using Android.App;
using Android.Content;
using Android.OS;
using AndroidX.Core.App;
using Xamarin.Forms;
// 必须加这行注册依赖服务,写在命名空间外
[assembly: Dependency(typeof(你的Android项目命名空间.AndroidNotificationManager))]

namespace 你的Android项目命名空间
{
    public class AndroidNotificationManager : INotificationManager
    {
        public const string TitleKey = "title";
        public const string MessageKey = "message";
        const string channelId = "default";
        const string channelName = "Default";
        const string channelDescription = "Default channel for notifications";
        int messageId = 0;

        public event EventHandler NotificationReceived;

        public void Initialize()
        {
            CreateNotificationChannel();
        }

        public void SendNotification(string title, string message, DateTime? notifyTime = null)
        {
            var intent = new Intent(Android.App.Application.Context, typeof(MainActivity));
            intent.PutExtra(TitleKey, title);
            intent.PutExtra(MessageKey, message);
            intent.AddFlags(ActivityFlags.SingleTop);

            var pendingIntent = PendingIntent.GetActivity(Android.App.Application.Context, 0, intent, PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);
            
            var notificationBuilder = new NotificationCompat.Builder(Android.App.Application.Context, channelId)
                .SetContentTitle(title)
                .SetContentText(message)
                .SetSmallIcon(Resource.Mipmap.icon)
                .SetContentIntent(pendingIntent)
                .SetAutoCancel(true);

            var notificationManager = NotificationManager.FromContext(Android.App.Application.Context);
            notificationManager.Notify(messageId++, notificationBuilder.Build());
        }

        public void ReceiveNotification(string title, string message)
        {
            NotificationReceived?.Invoke(this, new NotificationEventArgs { Title = title, Message = message });
        }

        void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                return;
            }
            var channel = new NotificationChannel(channelId, channelName, NotificationImportance.Default)
            {
                Description = channelDescription
            };
            var notificationManager = NotificationManager.FromContext(Android.App.Application.Context);
            notificationManager.CreateNotificationChannel(channel);
        }
    }
}

注意替换代码中的你的Android项目命名空间为你实际Android项目的命名空间。

2. 补充空值校验避免崩溃

修改你的订阅逻辑代码,增加空校验,同时主动调用Initialize方法初始化通知通道:

INotificationManager notificationManager;
int notificationNumber = 0;

notificationManager = DependencyService.Get<INotificationManager>();
// 增加空校验
if (notificationManager != null)
{
    // 初始化通知通道
    notificationManager.Initialize();
    notificationManager.NotificationReceived += (sender, eventArgs) =>
    {
        var evtData = (NotificationEventArgs)eventArgs;
        ShowNotification(evtData.Title, evtData.Message);
    };
}

void ShowNotification(string title, string message)
{
    Device.BeginInvokeOnMainThread(() =>
    {
        var msg = new Label()
        {
            Text = $"Notification Received:\nTitle: {title}\nMessage: {message}"
        };
        stacklayout.Children.Add(msg);
    });
}

3. 适配高版本Android权限

如果你的App targets Android 13(API 33)及以上版本,需要在AndroidManifest.xml中添加通知权限声明:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

且在发送通知前主动申请该运行时权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:57:02