Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load class based on SDK version

Is there any way I can load a class based on what version of the OS the phone is running? For example: I made an app which requires 1.6+ Android. Is there a way for me to load one class or the other based on what OS the phone is running? I'm asking this specifically for contacts. The database was changed from 1.6 to 2.0 and the old version doesn't retrieve contacts on the new OS phone. I'd still like to keep my 1.6 requirement, but at the same time I'd like 2.0+ phones to access the contact part of the app.

So can I make 2 APIs, somehow pack them with the app and decide on the fly which I choose to import?

like image 643
Bostjan Avatar asked Dec 28 '22 14:12

Bostjan


1 Answers

Yes! Here is a sample project illustrating the technique.

Step #1: Create an interface or abstract class describing what data you're trying to get across all API versions.

Step #2: Create concrete implementations/subclasses of the interface/abstract class, one for each API level.

Step #3: Somewhere, detect which one you need and use it. In my sample, I do this by looking at the android.os.Build.SDK value in a static context and creating a singleton of my "bridge" class.

like image 52
CommonsWare Avatar answered Jan 08 '23 08:01

CommonsWare