I'm writing an app that uses some functions and classes only available in the latest API level - 16, but I want it to run with no errors on devices with API level 15.
Let's use a couple of examples. A new class: Android.widget.Advanceable
, and a new/renamed method: View.setBackground()
:
I can do something like this:
Advanceable myAdvanceable = ...;
if (android.os.Build.VERSION.SDK_INT >= 16)
{
myView.setBackground(...);
myAdvanceable.advance();
}
else
{
myView.setBackgroundDrawable(...); // The old function name.
// Don't bother advancing advanceables.
}
And if I set a minSdk of 15 but a build target of 16 (i.e. in Project Properties->Android), it will actually compile with no errors. At least some of the time. Eclipse is a bit stochastic about the errors and will sometimes say "setBackground() is only available in API level >= 16" or similar, but if I just clean the project those errors magically go away.
So my question is, am I allowed to do this? Won't the code crash if I run it on an API level 15 device? Will it only crash if it actually gets to the 16 code? Why doesn't Eclipse stop me from building it?
Edit 1
Thanks for the answers, I guess the question should really be: Why won't lint warn me about using new APIs?
I have this in my manifest, and am using API level 16 functions but it still doesn't warn me:
<uses-sdk android:minSdkVersion="15"
android:targetSdkVersion="16"/>
Also I'm still not sure about when entire classes are new to an API level, such as Advanceable
. Specifically if I use them as member variables.
Edit 2
The answer turned out to be "Eclipse is buggy as hell", but Nico's answer was also very helpful.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…