Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to include a library based on API Level or an if statement for Android

Tags:

android

So I have a API issue. So i am creating a class that utilizes AndroidHttpClient to download Bitmap images from my server. Problem is, its API Level is 8 and I want this to be used from API 1 and above. Now I know I can use DefaultHttpClient (the API is Level 1) but is there a way I can use both, being distinguished by Build.VERSION.SDK (btw thanx for the quick respose, Konstantin Burov and iandisme).

So for example, if my device is 2.2 I use AndroidHttpClient, anything else use DefaultHttpClient.

Of course if I import the library it will give me an error on any device 1.5 to 2.1.

Any suggestions would greatly be appreciated, because in the future I would want to set other preferences based on API.

like image 414
rbz Avatar asked Dec 28 '22 08:12

rbz


2 Answers

I would do this by having two classes, each implementing an interface with the methods you need. Let's call the interface BitmapDownloader, and the two classes Downloader1 and Downloader2 (I know the class names suck but I'm not feeling terribly creative).

Downloader1 will import and use the old libraries, and Downloader2 will import and use the new ones. Your code would look something like this:

BitmapDownloader bd;
int version = Integer.parseInt(Build.VERSION.SDK);

if (version >= Build.VERSION_CODES.FROYO){
    bd = new Downloader2();
} else {
    bd = new Downloader1();
}

bd.doBitmapDownloaderStuff();
like image 147
iandisme Avatar answered Mar 02 '23 00:03

iandisme


There's a good developer blog article about it: http://android-developers.blogspot.com/2009/04/backward-compatibility-for-android.html

Basically, you compile your app for API level 8, make the minimum level as low as necessary (but keep the target level up). In your app, you can check for the existence of certain API classes that you wish to use.

Now here's the key: Any access to 2.2-only classes needs to be in separate .java files!! As soon you reference a class (call any of its static members, instantiate it, etc), the class loader will load the entire class and crash if it references anything that is not supported by the OS (i.e. 2.2 methods on a pre-2.2 system).

So call your methods with 2.2 functionality only after you verified that 2.2 is available. And that'll do.

like image 21
EboMike Avatar answered Mar 02 '23 00:03

EboMike