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

Xamarin Android 8.0本地通知无法显示,求助排查原因

解决Android 8.0中Xamarin通知不显示的问题

嘿,这个问题我刚好踩过类似的坑!Android 8.0(API 26)对通知机制做了强制变更,这正是你遇到问题的核心原因,咱们一步步来拆解:

为什么Android 8.0不显示通知?

从API 26开始,Android系统要求所有通知必须关联到一个已创建的通知渠道(NotificationChannel),如果没有指定渠道ID,系统会直接忽略该通知,而且不会抛出任何错误——这就是你在Android 8.0上看不到通知但无报错的原因。

你的代码哪里出了问题?

你已经正确创建了通知渠道,但在构建Notification.Builder的时候,针对Android O及以上版本,没有将渠道ID传递给Builder。在API 26+的设备上,Notification.Builder的构造方法需要额外传入渠道ID参数,否则通知无法和渠道关联,自然不会显示。

修改后的代码示例

只需要调整Notification.Builder的创建逻辑,根据系统版本选择对应的构造方法即可:

public void SendNotification(Context context, string message) 
{ 
    var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService); 

    if (Build.VERSION.SdkInt >= BuildVersionCodes.O) 
    { 
        var notificationChannel = new NotificationChannel(CHANNEL_ID, Strings.ApplicationName, NotificationImportance.High); 
        notificationManager.CreateNotificationChannel(notificationChannel); 
    } 

    var intent = new Intent(context, typeof(MainActivity)); 
    intent.AddFlags(ActivityFlags.ClearTop); 
    var pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot); 

    var bigstyle = new Notification.BigTextStyle(); 
    bigstyle.BigText(message); 
    bigstyle.SetBigContentTitle(Strings.ApplicationName); 

    // 关键修改:根据系统版本选择Builder构造方法
    Notification.Builder notificationBuilder;
    if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
    {
        // Android O+ 必须传入渠道ID
        notificationBuilder = new Notification.Builder(context, CHANNEL_ID);
    }
    else
    {
        // 低版本使用旧构造方法
        notificationBuilder = new Notification.Builder(context);
    }

    // 继续链式调用配置通知内容
    notificationBuilder
        .SetSmallIcon(Resource.Drawable.Icon) 
        .SetContentTitle(Strings.ApplicationName) 
        .SetContentText(message) 
        .SetAutoCancel(true) 
        .SetContentIntent(pendingIntent) 
        .SetStyle(bigstyle); 

    var notification = notificationBuilder.Build(); 
    notificationManager.Notify(MESSAGE_TYPE_DEFAULT, notification); 
}

额外注意点

  • 确保CHANNEL_ID是全局一致的常量,创建渠道时用的ID和Builder中传入的ID必须完全相同,否则关联会失败。
  • 通知渠道一旦创建,后续修改渠道的名称、重要性等属性不会生效,需要卸载应用重新安装或者通过代码手动更新渠道属性(如果需要调整的话)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:43:29