Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

I believe so, as long as everything is setup correctly.

From Reto Meier's blog: http://blog.radioactiveyak.com/2011/02/strategies-for-honeycomb-and-backwards.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top