Skip to content Skip to sidebar Skip to footer

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() { ... } @apilev

Solution 1:

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");
}
elseif (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:

interfaceImplBase {
voidmyFunc();
};

classICSImpimplementsImplBase {
publicvoidmyFunc(){}
}

classHoneyCombImpimplementsImplBase {
publicvoidmyFunc(){}
}

classLegaceImpimplementsImplBase {
publicvoidmyFunc(){}
}

Solution 2:

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

Post a Comment for "Different Java Methods For Different Api Levels"