ContentResolver读取联系人示例
Posted zhangjin1120
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ContentResolver读取联系人示例相关的知识,希望对你有一定的参考价值。
- 确保设备上有联系人,并且不要使用模拟器,模拟器存在不显示权限弹窗的bug。
- 在androidManifest.xml中添加权限:
<uses-permission android:name="android.permission.READ_CONTACTS" />
- MainActivity 代码:
package com.exp.cpdemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import java.security.Permission;
public class MainActivity extends AppCompatActivity
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
//读取联系人
readNameAndNums();
else
//申请权限
ActivityCompat.requestPermissions(MainActivity.this, new String[]Manifest.permission.READ_CONTACTS, 100);
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100)
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
//读取联系人
readNameAndNums();
else
Log.w(TAG, "onRequestPermissionsResult: 权限申请失败");
private void readNameAndNums()
String[] selectKey =
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
;
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
selectKey,
null,
null,
null
);
if (cursor != null && cursor.getCount() > 0)
int indexName = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNum = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
cursor.moveToFirst();
do
Log.i(TAG, "readNameAndNums: name: "+ cursor.getString(indexName)+" numbers:"+cursor.getString(indexNum));
while (cursor.moveToNext());
- 运行结果日志:
以上是关于ContentResolver读取联系人示例的主要内容,如果未能解决你的问题,请参考以下文章