Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Java methods for different API Levels

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

like image 386
J. Arenas Avatar asked Sep 23 '12 10:09

J. Arenas


2 Answers

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(){}
}
like image 100
marcinj Avatar answered Sep 21 '22 12:09

marcinj


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

like image 39
user387184 Avatar answered Sep 20 '22 12:09

user387184