Search code examples
androidandroid-compatibility

Android solving compatibility with SDK_INT hack; is this ok?


Running the following (note: target > 3.0)

ActionBar actionBar = getActionBar();

on Android with version < 3.0 (SDK 11) results in a NoSuchMethodError.

There are several ways to get around this, including reflection and class lazy loading. However, the following seems to work across all the devices I've tested (2.3.6, 3.0, 3.1, 4.0):

boolean hasActionBar = android.os.Build.VERSION.SDK_INT >= 11;

if (hasActionBar) {
    ActionBar actionBar = getActionBar();
} else {
    // create custom actionbar
}

Note the SDK_INT parameter is static final, which appears to be why this works.

Is this a valid way to deal with compatibility?


Solution

  • It looks like this works due to the JIT compiler. This code fails on SDK < 2.1, which supports this theory. Regardless, this probably isn't a reliable way to avoid reflection.