Android Studio 为什么方法在AS中显示为已弃用

soat7uwm  于 2023-02-24  发布在  Android
关注(0)|答案(2)|浏览(460)

我有下面的代码。为什么第二个stopForeground在Android Studio(Electric Eeel)中突出显示为弃用警告|2022年1月1日)?

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 
        }
     }
}

我使用的是compileSdk 33minSdk 21targetSdk 33,并且安装了Android SDK构建工具34-rc1

5anewei6

5anewei61#

如果你使用的是ServiceCompatstopForeground,按照文档你需要修改stopForeground(Boolean),并显式地传递STOP_FOREGROUND_REMOVESTOP_FOREGROUND_DETACH。根据你的compileSDK,它会抱怨或不抱怨,如果你有compileSDK 33,它会抱怨,因为在新的API版本中,他们已经修改了那个方法的签名。
ServiceCompat的源代码中,您正在尝试使用此stopForeground,您应该传递一个Service和一个flag

public static void stopForeground(@NonNull Service service, @StopForegroundFlags int flags) {
        if (Build.VERSION.SDK_INT >= 24) {
            Api24Impl.stopForeground(service, flags);
        } else {
            service.stopForeground((flags & ServiceCompat.STOP_FOREGROUND_REMOVE) != 0);
        }
    }

    @RequiresApi(24)
    static class Api24Impl {
        private Api24Impl() {
            // This class is not instantiable.
        }

        @DoNotInline
        static void stopForeground(Service service, int flags) {
            service.stopForeground(flags);
        }
    }

在内部,它们使用stopForeground

@Deprecated
    public final void stopForeground(boolean removeNotification) {
        throw new RuntimeException("Stub!");
    }

    public final void stopForeground(int notificationBehavior) {
        throw new RuntimeException("Stub!");
    }

因此,尝试使用import androidx.core.app.ServiceCompat.stopForeground的导入并检查错误是否仍然存在。
如果您在Service中执行此代码,您应该看到如下deprecation警告

尝试Invalidate cache and restart以查看是否存在IDE问题。

rjee0c15

rjee0c152#

该行突出显示为已过时,因为它过时。
虽然这是真的,但我觉得用一种让它看起来像错误或需要避免的东西的方式来突出显示这一点似乎很奇怪。这段代码是处理被弃用的方法的标准,所以也许不应该用一种让它看起来像错误的方式来突出显示...被弃用的代码行只运行在它没有被弃用的API级别上。

相关问题