你可以试试LoaderManager
创建以下字段
private static final int CONTACTS_LOADER_ID = 101;
private static final String[] PROJECTION = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
创建以下类
public class Contact {
private String id;
private String name;
private String number;
public Contact(String id, String name, String number) {
this.id = id;
this.name = name;
this.number = number;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
[1] 创建实例LoaderManager.LoaderCallback
private LoaderManager.LoaderCallbacks<Cursor> loaderCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id) {
case CONTACTS_LOADER_ID:
return new CursorLoader(
getActivity(),
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PROJECTION,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC"
);
default:
return null;
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case CONTACTS_LOADER_ID:
//Use ContactUtils class here
break;
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
};
[2] 使用以下类将游标数据转换为List<Contact>
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import java.util.ArrayList;
import java.util.List;
public class ContactUtils {
private ContactUtils() {
}
public static List<Contact> parseContacts(Cursor cursor) {
List<Contact> contacts = new ArrayList<>();
if (cursor.getCount() == 0) {
return contacts;
}
int nameColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY);
int idColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (cursor.moveToNext()) {
String contactName = cursor.getString(nameColumnIndex);
String id = cursor.getString(idColumnIndex);
String number = cursor.getString(numberColumnIndex);
Contact contact = new Contact(id, contactName, number);
if(!isContactAddedInList(contact, contacts)){
contacts.add(contact);
}
}
return contacts;
}
public boolean isContactAddedInList(Contact contact, List<Contact> contacts) {
for (Contact listContact : contacts
) {
if (listContact.number.equals(contact.name)) {
return true;
}
}
return false;
}
}
[3] 在你的 Fragment 或 Activity 的方法中调用getLoaderManager().initLoader
方法来加载联系人onStart
getLoaderManager().initLoader(CONTACTS_LOADER_ID, null, loaderCallbacks);
- 在清单文件中添加
<uses-permission android:name="android.permission.READ_CONTACTS" />
权限
- 您需要在调用之前请求运行时权限
getLoaderManager().initLoader