我正在制作一个使用联系人的Android应用程序。好消息是,我设法让它与Contacts.Phones一起工作,就像在许多教程中看到的那样。问题是Contacts.Phones已被弃用,并被ContactsContract所取代。我的应用程序需要从Android 1.5+开始工作。
我需要做一些简单的操作,如:-查询所有联系人-查询特定联系人-备份所有联系人
考虑到我需要让应用程序在所有版本的android上运行,那么实现这一目标的最佳方法是什么?我是否需要在手机上检查当前的api级别,并且有两个代码块,一个在api 5之前?
发布于 2011-08-03 21:24:50
这是一个可选的解决方案
int apiVersion = android.os.Build.VERSION.SDK_INT;
if(apiVersion < 5) {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(People.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(People._ID));
String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
}
}
} else {
String columns[] = new String[]{ ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
columns,
null,
null,
ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
long id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim();
}
}
}这里有一个使应用程序Supporting the old and new APIs in the same application的教程,这一定会对你有所帮助。
https://stackoverflow.com/questions/6926785
复制相似问题