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

Xamarin.Android中Notification.Notify调用无响应问题求助

问题分析与解决方案

你的问题完全是因为Android 8.0(API 26)引入的通知通道机制——从这个版本开始,系统要求所有通知必须绑定到一个已创建的通知通道才能显示,这就是你代码执行正常但看不到通知的核心原因,和清单配置无关(除非是更高版本的权限问题,但你的目标SDK是8.1,暂时不需要额外权限配置)。

解决步骤:

  • 首先需要创建一个通知通道(仅需在应用首次启动时创建一次,重复创建不会有问题)
  • 在通知构建器中指定该通道的ID

修改后的完整代码:

var message = intent.GetStringExtra("message");
var title = intent.GetStringExtra("title");
var notIntent = new Intent(context, typeof(MainActivity));
var contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent);
var manager = NotificationManagerCompat.From(context);

// --- 新增:创建通知通道(API 26+ 必需)---
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
    var channelId = "your_default_channel_id"; // 自定义通道ID,建议全局统一
    var channelName = "Default Notifications"; // 通道名称(用户可见)
    var channelDescription = "General notifications from the app"; // 通道描述(用户可见)
    var channelImportance = NotificationImportance.Default; // 通知重要性,决定提示方式

    var channel = new NotificationChannel(channelId, channelName, channelImportance)
    {
        Description = channelDescription
    };

    // 注册通道到系统
    var notificationManager = context.GetSystemService(Context.NotificationService) as NotificationManager;
    notificationManager?.CreateNotificationChannel(channel);
}
// --- 通道创建结束 ---

var style = new NotificationCompat.BigTextStyle();
style.BigText(message);
int resourceId = Resource.Drawable.ic_launcher;
var wearableExtender = new NotificationCompat.WearableExtender()
    .SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId));

// --- 修改:Builder中添加通道ID ---
var builder = new NotificationCompat.Builder(context, "your_default_channel_id") // 这里要和上面的通道ID一致
    .SetContentIntent(contentIntent)
    .SetSmallIcon(Resource.Drawable.ic_launcher)
    .SetContentTitle(title)
    .SetContentText(message)
    .SetStyle(style)
    .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
    .SetAutoCancel(true)
    .Extend(wearableExtender);

var notification = builder.Build();
manager.Notify(0, notification);

关键说明:

  1. 通知通道的重要性(NotificationImportance)决定了通知的提示方式,比如是否响铃、震动、显示在锁屏等,你可以根据需求调整为High、Max等级别。
  2. 通道创建后,用户可以在系统设置中修改通道的行为,应用无法再覆盖这些设置,所以建议设置合理的默认值。
  3. 如果你的应用需要多种类型的通知,可以创建多个不同的通道,分别绑定对应的通知。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:02:52