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

Android 13设置setOngoing(true)后通知仍可清除,求解决方案

Android 13前台服务通知无法保持不可清除的解决方案

问题场景

开发的前台服务依赖通知持续运行,但在Android 13系统中,用户可通过滑动清除通知导致应用终止。已调用setOnGoing(true)但未生效,需要实现通知不可被清除的效果。原代码如下:

private fun startForegroundServiceWithNotification() {
    Log.d("myTag", "startForegroundServiceWithNotification")
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = CHANNEL_ID
        val channelName = "Wish2Go step counter"
        val chan = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
        val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        service.createNotificationChannel(chan)
    }


    var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setOngoing(true)
        .setContentTitle("Counting steps")
        .setPriority(NotificationCompat.PRIORITY_HIGH)

    var notification = builder.build()
    notification.flags = Notification.FLAG_ONGOING_EVENT
    startForeground(1001, notification)

}

问题分析与解决步骤

  • 移除手动覆盖通知flags的代码:调用setOngoing(true)时,NotificationCompat.Builder会自动为通知添加FLAG_ONGOING_EVENT和FLAG_NO_CLEAR两个标记,二者共同保证通知不可被滑动清除。手动设置notification.flags = Notification.FLAG_ONGOING_EVENT会覆盖默认的flags集合,丢失FLAG_NO_CLEAR,这是问题的核心原因。
  • 确认Android 13通知权限:Android 13及以上系统需要显式申请POST_NOTIFICATIONS权限,需在Manifest中声明权限后,运行时请求用户授权,否则通知行为可能异常。
  • 检查通知渠道配置:确保通知渠道的重要性不设置为IMPORTANCE_MIN或IMPORTANCE_LOW,低优先级渠道可能导致通知被系统或用户设置影响,无法保持不可清除状态。

修正后的代码

private fun startForegroundServiceWithNotification() {
    Log.d("myTag", "startForegroundServiceWithNotification")
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = CHANNEL_ID
        val channelName = "Wish2Go step counter"
        val chan = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
        val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        service.createNotificationChannel(chan)
    }

    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setOngoing(true)
        .setContentTitle("Counting steps")
        .setPriority(NotificationCompat.PRIORITY_HIGH)

    val notification = builder.build()
    startForeground(1001, notification)
}

额外说明

如果仍存在问题,可尝试在创建通知渠道时添加chan.setAllowBubbles(false),避免气泡通知形式导致的清除行为异常;同时确保前台服务的启动流程符合Android系统规范,未被系统电池优化策略限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:17:28