13

Google's docs say to use this kind of code to ensure new code is not executed on old platforms:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
}

But when I do that, Eclipse still gives me warnings: "Call requires API level 11 (current min is 7)". What I want is to have my minimum version set to something lower than Honeycomb, have the above conditional statement protect me from running new code on old devices, and not have compiler warnings.

How do I do it?

FizzBuzz
  • 764
  • 6
  • 16

3 Answers3

10

Add @TargetApi(11) before method.

Benito Bertoli
  • 25,285
  • 12
  • 54
  • 61
  • 2
    For other folks reading this, @TargetApi seems a good place to start: add an import for android.annotation.TargetApi, then you can put @TargetApi(11) at the top of methods that target that version. Google's docs imply that you can put this inside conditional statements (http://tools.android.com/recent/lintapicheck), which is what I was asking about, but when I try that I get "The annotation TargetApi is disallowed for this location." – FizzBuzz Aug 16 '12 at 09:31
  • Do you have the latest ADT plugin? – Benito Bertoli Aug 16 '12 at 09:36
  • Yes; this is a new machine and I only set up the SDK/Eclipse/ADT on Monday. @TargetApi works fine at the top of methods, just not inside the conditional statement. – FizzBuzz Aug 16 '12 at 09:38
  • 1
    You can add the annotation to the method or to the class, but as you said, you cannot add it directly before a statement. – Benito Bertoli Aug 16 '12 at 11:40
2

@TargetApi() seems to be the best way to do this, Look up this page

Gautam
  • 7,868
  • 12
  • 64
  • 105
1

Java Annotations can only be applied to declarations and not to statements. The example in the lint documentation is cheating by beginning the if block with a variable declaration.

Martin
  • 11,577
  • 16
  • 80
  • 110