使用异步任务在后台加载联系人。首次加载后,将联系人列表存储到本地数据库中
https://developer.android.com/guide/components/loaders
https://stackoverflow.com/a/40017905/10239870
class ContactLoader extends AsyncTask<Void, Void, List<Contact>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//visible your progress bar here
}
@Override
protected List<Contact> doInBackground(Void... voids) {
List<Contact> contacts = new ArrayList<>();
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, order);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new Contact(name, phonenumber));
}
cursor.close();
return contacts;
}
@Override
protected void onPostExecute(List<Contact> contactList) {
super.onPostExecute(contactList);
//set list to your adapter
}
}
class Contact {
String name;
String number;
public Contact(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
}