Android solving compatibility with SDK_INT hack; is this ok?

只愿长相守 提交于 2019-12-19 11:57:10

问题


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?


回答1:


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




回答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.



来源:https://stackoverflow.com/questions/9183461/android-solving-compatibility-with-sdk-int-hack-is-this-ok

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!