Android: How do I call a method which is existing in other API Level?

eros picture eros · Sep 14, 2011 · Viewed 9.5k times · Source

I have application using Android 2.1 which utilize LocationManager to get the altitude. But now, I need to obtain the altitude using SensorManager which requires API Level 9 (2.3).

How can I put the SensorManager.getAltitude(float, float) in my 2.1 android application by putting a condition and calling it by a function name (possible in normal Java)?

Thank you in advance

UPDATE 1 If you have noticed that my application need to be compiled using Android 2.1. That's why I'm looking for a way to call the function by name or in any other way that can be compiled.

Answer

Rich picture Rich · Sep 14, 2011

You need to build against the highest api you require and then code alternate code paths conditionally for other levels you want to support

To check current API level at execution time, the latest recommendation from the Android docs is to do something like this:

    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD)
    {
        ...

Once you introduce this complexity though, you have to be very careful. There isn't currently an automatic way to check all code paths to make sure that all api level calls above the minSdkVersion have alternative calls to support all versions. Maybe someone can chime in if there exists a unit testing tool that might do something like this.