Search code examples
javaandroidversioningcompatibility

How to use 2.2 features if I target 2.1?


I like to use TrafficStats API in my application. Problem is - I target 2.1

It is really an addon to my application and it will function without this feature. What is the way to include this and keep app compatible with 2.1? I know I can start maintaining 2 APK's but It is something I don't want to do, seems to be troublesome. Is there any other way?


Solution

  • Is there any other way?

    Step #1: Set your project's build target to Android 2.2 (or higher, if you wish)

    Step #2: Wrap all calls to Android 2.2-specific features in version guard blocks:

    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.FROYO) {
      // do something only on 2.2
    }
    

    Step #3: Ensure your android:minSdkVersion is as low as you want (e.g., 7 for Android 2.1)

    Step #4: Run the occasional lint check to confirm that you are not accidentally using something particular to Android 2.2 outside of a version guard block