Android backwards compatibility: reflection versus simple conditional check -
i understand there (at least) 2 ways runtime checks ensure code doesn't call apis don't exist:
use conditional version number check, la
if (build.version.sdk_int >= build.version_codes.jelly_bean)
use java.lang.reflect , wrapper class techniques explained here: http://android-developers.blogspot.com/2009/04/backward-compatibility-for-android.html
but don't understand when 1 technique should used in lieu of other. reflection seems necessary when trying use android classes may not exist, since loading such class referenced in code cause fatal error. calling method belonging class know exists? example, on device running 2.2 (api 8):
protected void oncreate(bundle savedinstancestate) { if (build.version.sdk_int >= build.version_codes.froyo) { actionbar actionbar = getactionbar(); } ...
is always safe, or there circumstances crash happen? there reason check if "getactionbar" method exists in activity using reflection instead of using above version check?
but don't understand when 1 technique should used in lieu of other.
use first bulleted technique.
is safe, or there circumstances crash happen?
first, need change honeycomb
, actionbar
class added in api level 11.
beyond that, long supporting android 2.0 , higher, fine. if supporting android 1.x still, need rewrite code as:
if (build.version.sdk_int >= build.version_codes.honeycomb) { honeycombhelper.dosomethingcoolwiththeactionbar(); }
where honeycombhelper
class write contains api level 11 code (e.g., actionbar actionbar = getactionbar()
).
this difference because dalvik on android 1.x fail fast, giving verifyerror
try loading class contains unrecognized reference. android 2.0+ not fail until execute statement containing unrecognized reference, , if
test should prevent this.
is there reason check if "getactionbar" method exists in activity using reflection instead of using above version check?
no. set build target (e.g., project > properties > android in eclipse) value high enough cover want refer to, , set android:minsdkversion
level willing support. try using newer android:minsdkversion
flagged error lint, , can add java version guard block (if (build.version.sdk_int >= build.version_codes.whatever)
) , @targetapi()
annotation lint stop complaining.
Comments
Post a Comment