由于通讯录在手机里是以数据库贮存的 所以我们可以通过getContentResolver来获得通讯录 ,这个方法返回一个游标的数据类型,通过moveToNext()方法来获取所有的手机号码信息,

当然读取手机通讯录需要权限 在AndroidManifest文件中声明即可。由于我也实现了打电话的功能 所以也要声明权限。

1.添加权限 AndroidManifest里添加

//联系人
<uses-permission android:name="android.permission.READ_CONTACTS" />
//拨打电话
<uses-permission android:name="android.permission.CALL_PHONE" />

2.检查是否获得了权限,如果获得了权限,然后读取联系人;否则,去申请权限,申请成功读取联系人,申请失败,弹框提示授权失败。

public class MainActivity extends AppCompatActivity {

    ArrayAdapter<String> adapter;
List<String> contactsList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.contacts_view);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contactsList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//拨打电话
String number = contactsList.get(i);
Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+number));
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(intent);
}
}); //检查是否获得了权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.READ_CONTACTS},1);
} else {
readContacts();
}
} //读取联系人
private void readContacts() {
Cursor cursor = null;
try {
//内容提供器
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null
,null);
if (cursor != null) {
while (cursor.moveToNext()){
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(number);
}
//刷新列表
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null){
cursor.close();
}
}
} @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readContacts();
} else {
Toast.makeText(this,"获得联系人权限失败",Toast.LENGTH_SHORT).show();
}
break;
default: }
}
}
05-11 17:49