在AndroidManifest中申请读取联系人的权限
<uses-permission android:name = "android.permission.READ_CONTACTS"/>
package com.example.getcontacts;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
private static final String[] PHONES_PROJECTION = new String[] {
Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
private static final int PHONES_DISPLAY_NAME_INDEX = 0;
private static final int PHONES_NUMBER_INDEX = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void run(View v) {
getPhoneContacts();
}
private void getPhoneContacts() {
ContentResolver resolver = this.getContentResolver();
Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
PHONES_PROJECTION, null, null, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
Log.i("PHONECONTACT", "PhoneNumber:" + phoneNumber+ " ContactName:" + contactName);
}
phoneCursor.close();
}
}
}