示例图:
MainActivity.java
package com.example.mygetdata;import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;import java.net.URI;
import java.util.ArrayList;
import java.util.List;public class MainActivity extends AppCompatActivity {//组件private Button btnGet,btnAdd;private ListView listView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnGet = findViewById(R.id.btn_getDate);btnAdd = findViewById(R.id.btn_addData);listView = findViewById(R.id.list_view);//事件btnGet.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//获取联系人的方法getContacts();}});//添加联系人事件btnAdd.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {addContacts();}});//从6.0系统开始,需要动态获取权限int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);if (permissionCheck != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 0);}}//获取联系人@SuppressLint("Range")private void getContacts() {//获取内容解析对象ContentResolver contentResolver = getContentResolver();//需要解析的uri 获取系统手机的Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;/**查询数据 什么条件都没设置 查询所有信息* 得到一个游标对象* projection 显示哪些列* selection : 条件*sortOrder : 排序*/Cursor cursor = contentResolver.query(uri,null,null,null,null);List<String> arrData = new ArrayList<>();//循环遍历游标while (cursor.moveToNext()){//查到名字String name= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));//电话号String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));// 把数据添加到 集合arrData.add("姓名:"+name+"---"+number);}//关闭游标资源cursor.close();// 适配器ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,R.layout.list_data_layout,arrData);//往容器中添加适配器listView.setAdapter(arrayAdapter);}//添加联系人private void addContacts(){try {//获取内容解析对象ContentResolver contentResolver = getContentResolver();//需要解析的uri 数据中的2个表Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");Uri dataUri = Uri.parse("content://com.android.contacts/data");//批量插入数据ArrayList<ContentProviderOperation> operations = new ArrayList<>();ContentProviderOperation cpo = ContentProviderOperation.newInsert(uri).withValue("account_name",null).build();operations.add(cpo);//名字ContentProviderOperation cpo2 = ContentProviderOperation.newInsert(dataUri).withValueBackReference("raw_contact_id",0).withValue("mimetype","vnd.android.cursor.item/name").withValue("data2","添加测试").build();operations.add(cpo2);//电话号码ContentProviderOperation cpo3 = ContentProviderOperation.newInsert(dataUri).withValueBackReference("raw_contact_id",0).withValue("mimetype","vnd.android.cursor.item/phone_v2").withValue("data1","1111111111").withValue("data2","2").build();operations.add(cpo3);//邮箱ContentProviderOperation cpo4 = ContentProviderOperation.newInsert(dataUri).withValueBackReference("raw_contact_id",0).withValue("mimetype","vnd.android.cursor.item/email_v2").withValue("data1","1750691615@qq.com").withValue("data2","2").build();operations.add(cpo4);// 批量插入数据 把内容添加到手机contentResolver.applyBatch("com.android.contacts",operations);// 弹框Toast.makeText(getApplicationContext(),"添加成功",Toast.LENGTH_SHORT).show();} catch (Exception e) {Log.e("TAG",e.getMessage());Toast.makeText(getApplicationContext(),"添加失败"+e.getMessage(),Toast.LENGTH_SHORT).show();}}//请求权限结果@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);switch (requestCode){case 0:if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){Toast.makeText(MainActivity.this, "联系人权限授权成功", Toast.LENGTH_SHORT).show();//从6.0系统开始,需要动态获取权限int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS);if (permissionCheck != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CONTACTS}, 1);}}break;case 1:if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){Toast.makeText(MainActivity.this, "写入联系人权限授权成功", Toast.LENGTH_SHORT).show();}break;default:break;}}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn_getDate"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="获取联系人"android:textSize="24sp"/><ListViewandroid:id="@+id/list_view"android:layout_width="match_parent"android:layout_height="500dp"/><Buttonandroid:id="@+id/btn_addData"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="添加联系人"android:textSize="24sp"/>
</LinearLayout>
list_data_layout.xml
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"android:textColor="#ff00ff"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="22sp"/>
AndroidMainifest.xml 加入 读写权限
<!-- 配置权限 读写--> <uses-permission android:name="android.permission.READ_CONTACTS"/> <uses-permission android:name="android.permission.WRITE_CONTACTS"/>