这里获取通讯录的方式有问题,每获取一个联系人就要切换一次线程,求修改方法
public class MainActivity
extends AppCompatActivity {
private Context mContext;
private String TAG = "TAG";
ArrayList<ContactBean> contacts = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
mContext = MainActivity.this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doAction();
}
private void doAction() {
Observable.create(new Observable.OnSubscribe<Cursor>() {
@Override
public void call(Subscriber<? super Cursor> subscriber) {
ContentResolver contentResolver = mContext.getContentResolver();
Cursor cursor = contentResolver.query(
ContactsContract.RawContacts.CONTENT_URI,
null,
null,
null,
null
);
while (cursor.moveToNext()) {
subscriber.onNext(cursor);
}
cursor.close();
subscriber.onCompleted();
}
})
.map(new Func1<Cursor, ContactBean>() {
@Override
public ContactBean call(Cursor cursor) {
ContactBean contactBean = new ContactBean();
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactBean.setName(name);
//获取联系人号码
String id = cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
Cursor phoneCursor = mContext.getContentResolver()
.query(
android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
android.provider.ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,
null,
null
);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
contactBean.setTel(phoneNumber);
}
phoneCursor.close();
return contactBean;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ContactBean>() {
@Override
public void onCompleted() {
Toast.makeText(
mContext,
"length:" + contacts.size(),
Toast.LENGTH_SHORT
)
.show();
}
@Override
public void onError(Throwable e) {
Log.e(TAG,
"onError: ",
e
);
}
@Override
public void onNext(ContactBean contactBean) {
Log.i(
TAG,
"onNext: name:" + contactBean.getName() + " phone:" + contactBean.getTel()
);
contacts.add(contactBean);
}
});
}
}