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

Android Studio中stopForeground(true)为何显示已弃用?

问题:Android中stopForeground(true)被标记为已弃用警告的原因

使用Android Studio Electric Eeel | 2022.1.1版本,项目配置为compileSdk 33、minSdk 21、targetSdk 33,且已安装Android SDK Build-Tools 34-rc1,编写如下代码时,stopForeground(true)被标记为已弃用警告:

class FooService : android.app.Service() {
    fun bar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            stopForeground(STOP_FOREGROUND_REMOVE)
        } else {
            stopForeground(true) // This line shows as deprecated 
        }
     }
}

解答

原因分析

从API 24(Android 7.0,即N版本)开始,Android官方引入了带int flags参数的stopForeground(int flags)方法,用来替代原有的stopForeground(boolean removeNotification)方法。在API 33的SDK定义中,后者被正式标记为弃用。

你的项目compileSdk设置为33,Android Studio会依据compileSdk对应的SDK版本的API标记来检测代码中的弃用情况——哪怕你已经通过版本判断,只在低于API 24的设备上调用这个方法,编译器依然会基于当前compileSdk的API状态,给该代码行打上弃用警告。

解决办法

  1. 保留现有逻辑,忽略警告:你的代码本身是正确的兼容写法,弃用警告不会影响旧版本设备的正常运行,完全可以保留。
  2. 添加注解消除警告:如果不想看到警告,可以给该方法调用添加@Suppress("DEPRECATION")注解,修改后代码如下:
class FooService : android.app.Service() {
    fun bar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            stopForeground(STOP_FOREGROUND_REMOVE)
        } else {
            @Suppress("DEPRECATION")
            stopForeground(true)
        }
     }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:39:24