2

I wonder if it's possible to implement multiple methods to support different API levels and call the right one without if(android.os.Build.VERSION.SDK_INT >= ...) else if...?

I want to use android platform's newer features like streams etc. and still support backwards.

Example:

wrote a method

public void myMethod24() {
    // some logic requires api level N(24) and above
}

but my app supports lower apis, so i need another method that's compatible with them.

here is a method compatible for older versions:

public void myMethod21() {
    // the same logic, requires api level LOLLIPOP(21) and above
}

How to use the correct method for current running version without doing this ugly if else:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    myMethod24();
} else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
    myMethod21();
}

Maybe annotate my methods with @RequiresApi(), @TargetApi or something else..?

i saw this question but the answer there is with if else.

Community
  • 1
  • 1
ronginat
  • 1,910
  • 1
  • 12
  • 23

1 Answers1

1

How to use the correct method for current running version without doing this ugly if else

You can't. Somewhere, something needs to do the version check and route to the appropriate logic.

Maybe annotate my methods with @RequiresApi(), @TargetApi or something else..?

Those are there to help advise the compiler that you know what you are doing. They do not code-generate the version comparisons.

Depending on what you are doing, existing ...Compat classes might handle the version checks for you (e.g., NotificationCompat.Builder). If you were using Kotlin, we could come up with some funky code that hides the if checks. And there might be a third-party library that offers some annotation-based code generator that code-generates the if checks.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thank you for your answer. I know those annotation aren't the solution, just suggested that there is something similar that is. Right now i want to use java [Stream](https://developer.android.com/reference/java/util/stream/Stream) library that was added to android at API level 24. – ronginat Apr 07 '19 at 16:04
  • It isn't a problem to check the version myself, just searched for a way to do it simpler. – ronginat Apr 07 '19 at 16:10
  • How to handle a overriding a method that has different level of API support examlple is WebView `onReceivedError` one needs `Build.VERSION_CODES.M` or higher and the other one is lower than M. I do not think creating two separate `WebViewClient()` is intuitive approach – Bitwise DEVS Jun 21 '21 at 05:23