Is there any way to enable the library based on API level or if statement for Android

So I have a problem with the API. So I create a class that uses AndroidHttpClient to load bitmaps from my server. The problem is that its API level is 8 , and I want this to be used from API 1 and above . Now I know that I can use DefaultHttpClient (API level 1), but is there a way I can use both options, being different from Build.VERSION.SDK (thanx battles for quick repetition, Konstantin Burov and iandisme).

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

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

Any suggestions would be greatly appreciated because in the future I would like to set other settings based on the API.

+4
source share
3 answers

I would do this with two classes, each of which implements an interface using the methods you need. Let me call the interface BitmapDownloader , and the two classes are Downloader1 and Downloader2 (I know that class names suck, but I don't feel terribly creative). A.

Downloader1 will import and use the old libraries, and Downloader2 will import and use the new ones. Your code will 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(); 
+5
source

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

Basically, you are compiling your application for API level 8, make the minimum level as low as possible (but keep the target level higher). In your application, you can check for specific API classes that you want to use.

Now here's the key: any access to classes intended only for 2.2 should be in separate .java files! As soon as you access the class (call any of its static members, create an instance, etc.), the Class Loader will load the whole class and work if it refers to something that is not supported by the OS (for example, 2.2 pre methods -2.2 system).

Therefore, call your methods with functionality 2.2 only after you confirm that version 2.2 is available. And it will be done.

+3
source

This Android blog post may help.

http://android-developers.blogspot.com/2010/07/how-to-have-your-cupcake-and-eat-it-too.html

I found this mechanism quite useful.

+1
source

All Articles