Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...