Viktor Apoyan
Viktor Apoyan

Reputation: 10755

#ifdef in Android

I am writing an application for Android. My application must be launched under Android 2.2 and Android 4.0.3, and I want to use something like #ifdef in Android but I still can't find the way to do that.

Code example

Android 4.0.3

if( android.os.Build.VERSION.SDK == 4.0.3)
{
    String str = "foo";
    boolean b = str.isEmpty();
}

Android 2.2

else {
    String str = "foo";
    boolean b = str.length() == 0;
}

I can't write code like this as the compiler will give an error.

What you can suggest me to do ?

Upvotes: 2

Views: 4236

Answers (4)

Renetik
Renetik

Reputation: 6373

I found just recently that productFlavors is the way to do it. Using them you can create folders that are build just for the flavor thus conditionally compiling stuff. It's not the same but can solve similar situations.

Upvotes: 0

fabricemarcelin
fabricemarcelin

Reputation: 1759

You can simply check for the Api Level and call Build.VERSION.SDK_INT

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1007369

What you can suggest me to do ?

Newcomers to Java should spend time learning Java before starting in on Android development. 4.0.3 is not a valid integer in Java.

Instead, you should be using:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
 // do something
}

Upvotes: 5

mah
mah

Reputation: 39827

#ifdef is for compile-time processing, and even if that were generally an accepted practice in Java (it's not, but 3rd party tools do exist to support the concept), it would not likely help you, since you need to make a runtime decision about the environment you're running in (unless you want to generate multiple packages?).

As the link fabricemarcelin provided (http://stackoverflow.com/questions/3506792/android-api-version-programmatically) states, you can determine the version of your runtime system easily enough. You'll need to write your application to the API you know will exist at runtime (the 2.2 system, if that's your lower limit), and you'll need to make a runtime decision about calling the 4.0 functions. For 4.0 functionality, you'll likely need to find your APIs using reflection.

I've made use of reflection to access things otherwise only available on newer Android systems and it's worked well. One tip though is to arrange to perform the reflection / API location early in your application if reasonable, and if not, at least arrange to only do it once per call.

Upvotes: 1

Related Questions