Search code examples
androidconditional-compilation

Conditional compiling in Android?


Is there any kind of conditional compiling for Android?

I had to make my project for Android 3 (API 11) just because ExifInterface has almost no useful attributes in Android 2.3 (API 10), despite the fact that it appeared in API 5 (!!??). I don't want to restrict my app to ICS users.


Solution

  • You can check dynamically the current API version of the device and do different stuff depending on that:

        if(Build.VERSION.SDK_INT < 14) {
            // Crappy stuff for old devices
        }
        else {
            // Do awesome stuff on ICS
        }
    

    But be careful that if you need to instantiate classes that are not available for all APIs then you should do it in a runnable or in a separate wrapper class, e.g:

        if(Build.VERSION.SDK_INT < 14) {
            // Crappy stuff for old devices
        }
        else {
            // Do awesome stuff on ICS
            new Runnable() {
                new AmazingClassAvailableOnICS();
                (...)
            }.run();
        }