This commit is contained in:
Administrator committed 2026-05-23 01:12:40 +08:00
commit 2334555c7b
13 files changed
+206 -41

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
using Android.App;
using Android.Content;
using Android.OS;
using AndroidX.Core.App;
using SunlightAggregationTerminal;
// 使用 global:: 强制指定原生安卓的命名空间
using AndroidApp = global::Android.App;
namespace SunlightAggregationTerminal.Platforms.Android
{
public class NotificationService : INotificationService
{
const string channelId = "default_channel";
const string channelName = "Default Notifications";
const string channelDescription = "Default notification channel";
public void SendNotification(string title, string message, int notificationId = 0)
{
// 1. 创建通知渠道(仅 Android 8.0 / API 26 及以上需要)
#pragma warning disable CA1416 // 暂时关闭平台兼容性警告
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var channel = new AndroidApp.NotificationChannel(channelId, channelName, NotificationImportance.Default)
{
Description = channelDescription
};
// 修复点:获取系统服务并处理可能的 null 值
// 如果 GetSystemService 返回 null,则直接 return 终止方法,防止后续崩溃
var notificationManager = AndroidApp.Application.Context.GetSystemService(Context.NotificationService) as AndroidApp.NotificationManager;
if (notificationManager == null) return;
notificationManager.CreateNotificationChannel(channel);
}
#pragma warning restore CA1416 // 恢复平台兼容性警告
// 2. 构建通知内容
var intent = new Intent(AndroidApp.Application.Context, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
#pragma warning disable CA1416
// PendingIntent 同样建议做安全获取
var pendingIntent = PendingIntent.GetActivity(AndroidApp.Application.Context, 0, intent, PendingIntentFlags.Immutable | PendingIntentFlags.UpdateCurrent);
#pragma warning restore CA1416 // 恢复平台兼容性警告
NotificationCompat.Builder notificationBuilder;
// 核心兼容处理:根据系统版本选择不同的 Builder 构造方法
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
// Android 8.0+:必须传入 channelId
notificationBuilder = new NotificationCompat.Builder(AndroidApp.Application.Context, channelId);
}
else
{
#pragma warning disable CS0618
// Android 5.0 ~ 7.x:不支持 channelId,使用旧版单参数构造方法
notificationBuilder = new NotificationCompat.Builder(AndroidApp.Application.Context);
#pragma warning restore CS0618
}
var notification = notificationBuilder!
.SetContentTitle(title)!
.SetContentText(message)!
// 请确保你的 Resources/drawable 文件夹下有这个图标
//.SetSmallIcon(Resource.Drawable.abc_vector_test)!
.SetAutoCancel(true)!
.SetContentIntent(pendingIntent);
// 如果是 Android 5.0 (API 21) 及以上,还可以设置锁屏可见等特性
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
notification!.SetVisibility(NotificationCompat.VisibilityPublic);
}
// 3. 发送通知
var compatManager = NotificationManagerCompat.From(AndroidApp.Application.Context);
compatManager!.Notify(notificationId, notification!.Build());
}
}
}