Xamarin.Forms中StartForeground服务后台运行时如何隐藏应用运行通知
能否隐藏前台服务运行通知
安卓系统对前台服务的通知管控按版本区分,不存在全版本通用的完全隐藏方案:
1. 安卓8.0(API 26)及以上版本
系统强制要求所有前台服务必须绑定通知渠道并展示运行通知,无法彻底隐藏,但可以通过配置最大程度降低通知的存在感:
- 创建通知渠道时将重要等级设为
NotificationImportance.Min,此时通知默认静音、无振动、不会主动弹出,仅会收纳在通知栏最底部的折叠区域,用户不主动展开通知栏几乎感知不到 - 你当前代码中重复设置了静音、振动属性,且
SetOngoing(false)配置无效,前台服务通知会被系统强制设为常驻状态 - 可将通知渠道名称设为「后台运行」这类低感知的文案,进一步降低用户关注度
2. 安卓7.1(API 25)及以下版本
系统无强制前台服务通知展示的要求,可以通过调用StopForeground(true)的方式移除通知,同时保持服务的前台优先级不被系统回收。
优化后的代码示例
// 仅API 26及以上需要创建通知渠道 if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel(channelId, "后台运行", NotificationImportance.Min); channel.SetSound(null, null); channel.EnableVibration(false); channel.SetShowBadge(false); var notificationManager = GetSystemService(NotificationService) as NotificationManager; notificationManager.CreateNotificationChannel(channel); } NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId) .SetSmallIcon(Resource.Drawable.navigation_empty_icon) .SetPriority(NotificationCompat.PriorityMin) .SetContentTitle("") .SetContentText("") .SetSilent(true) .SetOngoing(true); StartForeground(1, builder.Build()); // API 25及以下执行这行即可隐藏通知 if (Build.VERSION.SdkInt < BuildVersionCodes.O) { StopForeground(true); }
注意事项
- 部分国产定制ROM会默认将低优先级的前台服务通知收纳到「不重要通知」分组,用户感知度极低
- 不要使用非常规手段强制隐藏API 26及以上版本的前台服务通知,安卓12及以上系统会直接杀死应用并抛出异常
内容的提问来源于stack exchange,提问作者Taghi Poorchi
相关产品推荐
相关产品推荐

