.NET 7 MAUI中Plugin.LocalNotification在Android发布模式异常问题
Plugin.LocalNotification在.NET 7 MAUI Android平台的兼容问题排查与修复
问题现象
- iOS 17环境运行完全正常
- Android平台存在多场景异常:
- API ≤33调试模式:正常工作
- API 34调试模式、API ≤33发布模式:无任何反应,应用日志输出
SendNotification: Notification 100 has no NotifyTime - API 34发布模式:触发通知时应用直接崩溃
涉事代码片段
var notification = new NotificationRequest { NotificationId = 100, Title = "Test", Description = "Test Description", ReturningData = "Dummy data", Schedule = { NotifyTime = DateTime.Now.AddSeconds(10) } };
针对性修复方案
1. 解决Schedule未实例化导致的NotifyTime丢失问题
日志提示的核心问题是Schedule对象未被正确创建,直接用嵌套初始化器赋值子属性的写法,在发布模式或高API版本的JIT优化下会失效。必须显式实例化NotificationRequestSchedule:
var notification = new NotificationRequest { NotificationId = 100, Title = "Test", Description = "Test Description", ReturningData = "Dummy data", Schedule = new NotificationRequestSchedule { NotifyTime = DateTime.Now.AddSeconds(10) } };
2. API 34(Android 14)权限适配
Android 14强制要求POST_NOTIFICATIONS权限,两步搞定:
- 在
AndroidManifest.xml中声明权限:<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> - 运行时动态申请(发布模式下必须):
if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu) { var status = await Permissions.CheckStatusAsync<Permissions.PostNotifications>(); if (status != PermissionStatus.Granted) { status = await Permissions.RequestAsync<Permissions.PostNotifications>(); } }
3. 发布模式下的链接器配置优化
发布模式的代码压缩可能破坏插件的反射逻辑,需在Linker.xml中保留插件相关程序集:
<linker> <assembly fullname="Plugin.LocalNotification" /> <assembly fullname="Plugin.LocalNotification.Android" /> </linker>
或者在项目文件中设置链接行为为SdkOnly,避免过度压缩:
<PropertyGroup Condition="'$(TargetFramework)' == 'net7.0-android'"> <AndroidLinkMode>SdkOnly</AndroidLinkMode> </PropertyGroup>
4. API 34崩溃问题修复
崩溃通常和通知渠道未配置有关,Android 8.0及以上必须创建通知渠道:
if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel("default", "Default Channel", NotificationImportance.Default); channel.Description = "Default Notification Channel"; var notificationManager = (NotificationManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.NotificationService); notificationManager.CreateNotificationChannel(channel); }
同时在通知请求中指定渠道ID:
var notification = new NotificationRequest { // ...其他属性 Android = new AndroidOptions { ChannelId = "default" } };
内容的提问来源于stack exchange,提问作者crymuch
相关产品推荐
相关产品推荐

