Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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

like image 248
Tenfour04 Avatar asked Jul 31 '11 17:07

Tenfour04


3 Answers

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.

like image 171
Learn OpenGL ES Avatar answered Oct 30 '22 16:10

Learn OpenGL ES


This worked for me:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){
            //code 
}
like image 29
Leonardo Benedeti Avatar answered Oct 30 '22 15:10

Leonardo Benedeti


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

like image 1
smith324 Avatar answered Oct 30 '22 14:10

smith324