Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ContactsContract and building across multiple SDK versions

I need my app to run on all Android versions, but the Contacts API changed in 2.0.

In SDK 1.6 and earlier I use android.provider.Contacts to query the contacts DB, but this does not work in 2.0

Instead, for 2.0 I use android.provider.ContactsContract. This presents a problem: when I have code for ContactsContract, my app will not build for 1.6 and earlier.

Do I need to have two separate versions of my app (one for <= 1.6 and one for 2.0 and later) or is there a way to avoid doing this?

like image 700
jlim Avatar asked Feb 27 '23 19:02

jlim


1 Answers

You can support both versions on Android using Java Reflection. Amusingly, the answer to your question can be found in a recent question about reflection used to solve this exact problem:

Uri baseUri = Contacts.Phones.CONTENT_FILTER_URL;
try {
    Class<?> c = Class.forName("android.provider.ContactsContract$PhoneLookup");
    baseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(baseUri);
} 
    catch (Exception e) {
}
like image 166
Dan Lew Avatar answered Apr 09 '23 13:04

Dan Lew