Android 13(MAUI Android)中如何通过Worker发送通知?
在Worker中使用Plugin.LocalNotifications发送通知失败的解决方案
针对你遇到的问题,以下是几个关键排查点和解决步骤:
1. 必须创建通知渠道(Android 8.0+强制要求)
Android 8.0(API 26)及以上版本,所有通知必须绑定到指定渠道才能显示。你需要先创建通知渠道,再发送通知:
public override Result DoWork() { // 先创建通知渠道 var channelRequest = new NotificationChannelRequest { Id = "periodic_task_channel", Name = "周期性任务通知", Description = "用于显示Worker触发的通知", Importance = NotificationImportance.Default }; LocalNotificationCenter.Current.CreateNotificationChannel(channelRequest); // 再构建并发送通知请求 NotificationRequest miRequest = new NotificationRequest { NotificationId = 1000, Title = "Título de notificación", BadgeNumber = 42, Schedule = new NotificationRequestSchedule { NotifyTime = DateTime.Now, }, ChannelId = "periodic_task_channel" // 绑定到创建的渠道 }; LocalNotificationCenter.Current.Show(miRequest); return Result.InvokeSuccess(); }
2. 动态申请POST_NOTIFICATIONS权限(Android 13+)
清单中添加权限只是第一步,Android 13(API 33)及以上需要在应用前台时主动请求用户授权,后台Worker无法触发权限弹窗:
在MainActivity的OnCreate方法中添加权限请求代码:
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // 请求通知权限 if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu) { RequestPermissions(new string[] { Manifest.Permission.PostNotifications }, 1001); } }
3. 规避Android后台限制
Android的Doze模式、App Standby等机制会限制后台组件的通知展示,可将Worker设为前台服务提升优先级:
- 在清单中添加前台服务权限:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
- 在Worker的
DoWork方法开头设置前台状态:
public override Result DoWork() { // 创建前台服务通知 var foregroundNotification = new Android.App.Notification.Builder(Android.App.Application.Context, "periodic_task_channel") .SetContentTitle("任务执行中") .SetContentText("正在处理周期性任务") .SetSmallIcon(Resource.Drawable.ic_notification) // 替换为你的通知图标 .Build(); // 将Worker设为前台服务 SetForegroundAsync(new ForegroundInfo(1001, foregroundNotification)); // 后续的通知发送逻辑... return Result.InvokeSuccess(); }
4. 验证插件初始化
确保在应用启动时完成Plugin.LocalNotifications的初始化,比如在MainApplication的OnCreate中:
public override void OnCreate() { base.OnCreate(); LocalNotificationCenter.Current.Initialize(); }
5. 调整通知触发时间
你设置的NotifyTime = DateTime.Now可能因系统调度延迟导致通知被跳过,可尝试设置一个小幅延后的时间:
Schedule = new NotificationRequestSchedule { NotifyTime = DateTime.Now.AddSeconds(2), };
如果不需要定时,直接移除Schedule属性,发送即时通知。
内容的提问来源于stack exchange,提问作者Álvaro García
相关产品推荐
相关产品推荐

