.NET MAUI中MvvmCommunityToolkit Badge异常:Google Pixel角标不显示
MAUI Badge在Google Pixel设备上不显示的问题排查与解决
问题背景
尝试通过.NET MAUI Community Toolkit的Badge组件在应用图标上显示通知数量,但未达到预期效果。已遵循官方文档操作,但文档未提供Google Pixel设备的权限配置说明。
现有代码实现
ViewModel中的Badge使用
private readonly IBadge badge; public RequestViewModel(IBadge badge) { this.badge = badge; } [RelayCommand] private async Task ViewDetails() { badge.SetCount(2); }
MauiProgram.cs配置
var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .UseMauiCommunityToolkit() .RegisterAppServices() .UseMauiCommunityToolkit() .RegisterViewModels() .RegisterViews() .ConfigureMopups() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); fonts.AddFont("fa-solid-900.ttf", "Icons"); fonts.AddFont("Poppins-Regular.ttf", "Poppins"); }); builder.Services.AddMemoryCache(); builder.Services.AddSingleton<IBadge>(Badge.Default);
Google Pixel设备的额外配置
Google Pixel基于原生Android系统,需补充以下配置才能让应用图标角标正常显示:
- 添加权限声明
在Platforms/Android/AndroidManifest.xml中添加通知权限:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
- 动态请求通知权限
Android 13(API 33)及以上版本要求动态申请通知权限,需在调用Badge前执行权限请求:
private async Task RequestNotificationPermission() { if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu) { var status = await Permissions.CheckStatusAsync<Permissions.Notifications>(); if (status != PermissionStatus.Granted) { status = await Permissions.RequestAsync<Permissions.Notifications>(); } } }
可在应用启动逻辑(如MainActivity的OnCreate)或ViewModel初始化时调用此方法。
- 初始化通知渠道
MAUI Community Toolkit的Badge在Android端依赖通知渠道,需提前创建有效渠道:
private void CreateNotificationChannel() { if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channelId = "badge_channel"; var channelName = "Badge Notifications"; var channelDescription = "用于更新应用图标角标的通知渠道"; var channel = new NotificationChannel(channelId, channelName, NotificationImportance.Default) { Description = channelDescription }; var notificationManager = (NotificationManager)GetSystemService(NotificationService); notificationManager.CreateNotificationChannel(channel); } }
建议在MainActivity的OnCreate方法中调用该方法完成初始化。
额外注意事项
- 确保.NET MAUI Community Toolkit已更新至最新稳定版本,避免版本兼容问题。
- 部分Pixel设备的Launcher可能需要重启应用或设备,才能让角标显示生效。
内容的提问来源于stack exchange,提问作者Sparsh
相关产品推荐
相关产品推荐

