You need to enable JavaScript to run this app. Xamarin.Forms跨平台本地通知操作按钮实现技术咨询
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms跨平台本地通知操作按钮实现技术咨询

Xamarin.Forms 本地通知添加操作按钮及响应实现

Android 平台实现

1. 创建通知渠道(Android 8.0+ 必需)

Android 8.0(API 26)及以上版本要求通知必须归属指定渠道,可在MainActivity或后台服务中创建:

private void CreateNotificationChannel()
{
    if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
    {
        var channelId = "action_notification_channel";
        var channelName = "操作通知渠道";
        var channelDescription = "带操作按钮的通知渠道";
        var channel = new NotificationChannel(channelId, channelName, NotificationImportance.Default)
        {
            Description = channelDescription
        };

        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }
}

2. 定义操作按钮与PendingIntent

先创建接收按钮点击事件的自定义广播接收器:

[BroadcastReceiver(Enabled = true)]
public class NotificationActionReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        var action = intent.GetStringExtra("action");
        switch (action)
        {
            case "confirm":
                MessagingCenter.Send<object, string>(this, "NotificationAction", "确认按钮被点击");
                break;
            case "cancel":
                MessagingCenter.Send<object, string>(this, "NotificationAction", "取消按钮被点击");
                break;
        }
    }
}

再为每个按钮绑定对应的PendingIntent:

var confirmIntent = new Intent(this, typeof(NotificationActionReceiver));
confirmIntent.PutExtra("action", "confirm");
var confirmPendingIntent = PendingIntent.GetBroadcast(this, 0, confirmIntent, PendingIntentFlags.UpdateCurrent);

var cancelIntent = new Intent(this, typeof(NotificationActionReceiver));
cancelIntent.PutExtra("action", "cancel");
var cancelPendingIntent = PendingIntent.GetBroadcast(this, 1, cancelIntent, PendingIntentFlags.UpdateCurrent);

3. 构建并发送带操作按钮的通知

使用NotificationCompat.Builder添加操作按钮后发送:

var channelId = "action_notification_channel";
var notificationBuilder = new NotificationCompat.Builder(this, channelId)
    .SetSmallIcon(Resource.Drawable.ic_notification)
    .SetContentTitle("带操作的通知")
    .SetContentText("点击按钮执行对应操作")
    .SetPriority(NotificationCompat.PriorityDefault)
    .AddAction(Resource.Drawable.ic_confirm, "确认", confirmPendingIntent)
    .AddAction(Resource.Drawable.ic_cancel, "取消", cancelPendingIntent);

var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(1001, notificationBuilder.Build());

iOS 平台实现

1. 请求通知权限并注册通知类别

在AppDelegate的FinishedLaunching方法中完成权限请求与类别注册:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Badge, (granted, error) =>
    {
        if (granted)
        {
            DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                UIApplication.SharedApplication.RegisterForRemoteNotifications();
                RegisterNotificationCategories();
            });
        }
    });

    UNUserNotificationCenter.Current.Delegate = this;
    return base.FinishedLaunching(app, options);
}

private void RegisterNotificationCategories()
{
    var confirmAction = UNNotificationAction.FromIdentifier("confirm", "确认", UNNotificationActionOptions.None);
    var cancelAction = UNNotificationAction.FromIdentifier("cancel", "取消", UNNotificationActionOptions.None);

    var category = UNNotificationCategory.FromIdentifier("action_notification_category", new[] { confirmAction, cancelAction }, new string[] {}, UNNotificationCategoryOptions.None);

    UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(category));
}

2. 构建并发送本地通知

创建关联类别的通知请求并发送:

var content = new UNMutableNotificationContent();
content.Title = "带操作的通知";
content.Body = "点击按钮执行对应操作";
content.CategoryIdentifier = "action_notification_category";
content.Sound = UNNotificationSound.Default;

var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(10, false);
var request = UNNotificationRequest.FromIdentifier("action_notification_request", content, trigger);

UNUserNotificationCenter.Current.AddNotificationRequest(request, (error) =>
{
    if (error != null)
    {
        // 处理错误逻辑
    }
});

3. 处理按钮点击事件

在AppDelegate中实现通知代理的响应方法:

[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
    switch (response.ActionIdentifier)
    {
        case "confirm":
            MessagingCenter.Send<object, string>(this, "NotificationAction", "确认按钮被点击");
            break;
        case "cancel":
            MessagingCenter.Send<object, string>(this, "NotificationAction", "取消按钮被点击");
            break;
        case UNNotificationDefaultActionIdentifier:
            // 用户点击通知本身的处理逻辑
            break;
    }

    completionHandler();
}

Xamarin.Forms 层统一处理

在Forms页面中订阅MessagingCenter接收操作事件:

public MainPage()
{
    InitializeComponent();
    MessagingCenter.Subscribe<object, string>(this, "NotificationAction", (sender, action) =>
    {
        DisplayAlert("通知操作", $"触发操作:{action}", "确定");
        // 此处添加业务逻辑处理
    });
}

也可通过依赖注入封装统一调用接口:

public interface INotificationService
{
    void SendNotificationWithActions(string title, string body);
}

在Android和iOS项目中实现该接口后,通过DependencyService调用:

DependencyService.Get<INotificationService>().SendNotificationWithActions("测试通知", "带操作按钮的通知");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:45:41