开发者

Is reflection necessary if I use "if (android.os.Build.VERSION.SDK_INT>=11)"

I'm working on an app that targets API 11 (3.0) but minSDKVersion is 7 (2.1).

I generate my PreferenceActivity programmatically instead of with XML. In Honeycomb, preference layouts have a built-in spot for an icon that can go next to each preference. You can set it with prefScreen.setIcon(R.drawable.my_icon);

So I don't want to do this on API 7-10. Is this sufficient protection 开发者_Go百科from crashes?

if (android.os.Build.VERSION.SDK_INT>=11)
    prefScreen.setIcon(R.drawable.myIcon);

The more elaborate solution that I know is safe is to use reflection to check if that method exists before trying to use it.


According to http://developer.android.com/training/basics/activity-lifecycle/starting.html, it's implied that it's safe to use the SDK_INT constant on Android 2.0 and above to wrap calls to newer APIs, without using reflection.

Caution: Using the SDK_INT to prevent older system's from executing new APIs works in this way on Android 2.0 (API level 5) and higher only. Older versions will encounter a runtime exception.


This worked for me:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){
            //code 
}


If the method is not available on a lower versions of the platform, it will crash when the file is loaded by the system (it won't even make it to execution of your if statement)

You should look at the article on Lazy Loading to do the reflection on the Android Dev Blog

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜