Home » Android » android – Different Java methods for different API Levels

android – Different Java methods for different API Levels

Posted by: admin June 15, 2020 Leave a comment

Questions:

How can you make a method with some versions each for a different API level. I think it’s something like this, but I’m not sure

@apilevel("11")
private void getR()
{
...
}

@apilevel("4")
private void getR()
{
...
}

What is the correct way to do this? Thanks in advance

How to&Answers:

You may use:

Integer.valueOf(android.os.Build.VERSION.SDK);

For reference you may like to check here: http://developer.android.com/reference/android/os/Build.VERSION.html#SDK

And for the levels themselves here is the list: http://developer.android.com/guide/topics/manifest/uses-sdk-element.html

Answer:

here you will find very good text on this subject:

http://android-developers.blogspot.com/2010/07/how-to-have-your-cupcake-and-eat-it-too.html

you basicly should use code like below:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    Log.i(LOG_TAG, "At least ICS version");
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    Log.i(LOG_TAG, "At least HoneyComb version");
}
else {
    Log.i(LOG_TAG, "legacy");
}

const values like ICE_CREAM_SANDWICH are statically put into java classes, so as long as they are available during compilation, they will be available also on previous android sdk-s on user phones. What you dont want to do is to call methods that are not available on previous sdk-s, this will end with VFY exceptions.

but this can be tedious to write code like that, thats why its best to create separate implementation for each android version and access it thought base interface:

interface ImplBase {
void myFunc();
};

class ICSImp implements ImplBase {
public void myFunc(){}
}

class HoneyCombImp implements ImplBase {
public void myFunc(){}
}

class LegaceImp implements ImplBase {
public void myFunc(){}
}