【问题标题】:Why does method show as为什么方法显示为
【发布时间】:2023-02-22 20:20:33
【问题描述】:

我有以下代码。为什么第二个 stopForeground 在 Android Studio ( Electric Eeel | 2022.1.1) 中突出显示为错误?

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    stopForeground(STOP_FOREGROUND_REMOVE)
} else {
    stopForeground(true)  // This line highlighted as error in AS
}

【问题讨论】:

  • 使用 ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) ... 谷歌有时 f..up lint ... fx 我已经用 java 代码测试了你的代码并且 lint 没有突出显示 ... 也许这取决于使用的构建工具(我使用的是 33.0 .2)
  • 你能从你的构建中提供 compileSdkVersion、buildToolsVersion、minSdkVersion 和 targetSdkVersion 吗?正如我用 33、'33.0.2'、22、33 和 java 而不是 kotlin 写的那样,这段代码不会引起高亮
  • 要获得有关您的代码的更多信息,请发布您调用此代码的位置(活动或服务)以及@Selvin 对 minSdk、compileSdkVersion 等的评价...

标签: android android-studio


【解决方案1】:

如果您使用ServiceCompatstopForeground,则在documentation 之后,您需要更改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 问题。

【讨论】:

  • 您需要更改 stopForeground(Boolean) 并传递 STOP_FOREGROUND_REMOVE他不能,因为他的 minSdkVersion 低于 24 并且没有 stopForeground(int) ...并且 lint 不应该抱怨这个,因为他正在做 Build.VERSION.SDK_INT >= Build.VERSION_CODES.N 检查 ...所以这很可能是 lint 中的一个错误... compileSDK 33 没关系 lint 应该考虑 minSdkVersion
  • 检查不是必需的,因为它在 stopForeground 内部进行检查,如果他有 minSdk 让我们说 23 和 targetSdk 到 33,ServiceCompat.stopForeground 中的方法需要一个服务和一个标志
  • 你没有在答案中写到 ServiceCompat 而他没有使用它......他从自己的服务中调用它
  • ServiceCompat 使用服务方法
  • @Selvin,好吧,我已经用一些数据编辑了答案..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
  • 1970-01-01
相关资源
最近更新 更多