Writing backwards compatible Android code Writing backwards compatible Android code android android

Writing backwards compatible Android code


Inline Api errors are new to ADT, Eclipse run Lint (and I guess something else maybe) to analyze your code and put those errors / warnings inline. The same apply to xml layout when you have warnings or hints about optimizations or best practices. You can use Annotations to suppress those errors in the class or in a particular method.

@TargetApi(16)
@SuppressLint("NewApi")

There is a problem in the sample code you put here, beside the API level check you have an instance of Advanceable in the code that will not work in API < 16, so checking API level is only useful when you call new methods but you cant reference new API classes outside the IF block.

One approach I found acceptable is to create an abstract class and two implementations, then to instantiate the correct implementation you can use a factory class with static methods.

For example to create a view that use some new API classes and methods internally you need:

1 - Create abstract class:

public abstract class CustomView {    public abstract void doSomething();}
  • Common implementation compatible with all APIs
  • Define abstract method here to split implementation

2 - Legacy implementation

public class CustomLegacyView extends CustomView {    public void doSomething(){        //implement api < 16    }}
  • implement the abstract method for API < 16

3 - API 16 implementation

@TargetApi(16)public class CustomL16View extends CustomView {    Advanceable myAdvanceable;    public void doSomething(){        //implement api >= 16    }}
  • Use annotation @TargetApi(16)
  • implement the abstract method for API >= 16
  • You can reference level 16 classes here (but not in CustomView)

4 - Factory class

public class ViewFactory {    public static CustomView getCustomView(Context context) {        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {            return new CustomL16View(context);        }else{            return new CustomLegacyView(context);        }    }}


It is a common practice to use a newer build target and guarantee newer API will be called in the right circumstances. Google even added @TargetApi() annotation since ADT 17 to specify local overrides for conditionally loaded code.

See Lint API check for more details.


1. You have Target Api and Minimum SDK attributes to define what kind of device are you targeting and which will be the least Api version on which it will run.

2. Target Api will be the one on which the App runs with Full features, whereas Minimum SDK will make the App run on it with some Compromises as there can be chances that the lower API version dont have the features which are in its higher versions.