11

The annotation @RequiresApi is helpful for requiring that the annotated element is only called on the given API level or higher. However, there does not appear to be a corresponding annotation for requiring that the annotated element is only called on the given API or lower.

For example, given something like:

@RequiresMaxApi(28) // or @DeprecatedSinceAndroid(29)
fun doSomethingWithExternalStorage() {
    val dir = Environment.getExternalStorageDirectory() // This is deprecated in API 29
    // ...
}

Calling doSomethingWithExternalStorage() from code that does not include a check like:

if (VERSION.SDK_INT < 29) {
    doSomethingWithExternalStorage()
}

Without the above API check, doSomethingWithExternalStorage() would display a lint error/warning, similar to how @RequiresApi does.

From my understanding, this is also similar to how @DeprecatedSinceKotlin works.

Is there an existing annotation that meets these requirements, or is there another way to achieve the desired result?

ashughes
  • 7,155
  • 9
  • 48
  • 54
  • You should already be getting a deprecation indicator (strikethrough) if your `compileSdkVersion` is 29 or higher. And I think that there is a compiler flag that you can set to fail builds on deprecation warnings. – CommonsWare Oct 01 '20 at 22:17
  • 1
    @CommonsWare That's not what I want though. Just because something's deprecated, doesn't mean that wasn't the correct (or possibly only) way to do something on previous API versions. I want to be able to scope code with an annotation that prevents it from being used on API X and later until the `minSdkVersion` is bumped high enough to remove the code entirely. – ashughes Oct 01 '20 at 22:40
  • 1
    hmmmm what about [create it](https://engineering.wework.com/custom-annotations-in-android-af43514f2f1b) :) – Saif Hamed Oct 02 '20 at 00:54

0 Answers0