Android -- ContentProvider, 读取和保存系统 联系人
1. 示例代码
需要的读写联系人的权限
<uses-permission android:name="android.permission.WRITE_CONTACTS"/> <uses-permission android:name="android.permission.READ_CONTACTS"/>
读联系人代码
public void click(View view) { ContentResolver resolver = getContentResolver(); // raw_contact 表的uri Uri uri = Uri.parse("content://com.android.contacts/raw_contacts"); // data 表的uri Uri dataUri = Uri.parse("content://com.android.contacts/data"); Cursor cursor = resolver.query(uri, new String[] { "contact_id" }, null, null, null); while (cursor.moveToNext()) { String id = cursor.getString(0); //系统删除联系人的时候不会删除全部db中的信息,只是将id置为 null if (id != null) { Cursor dataCursor = resolver.query(dataUri, new String[] { "data1", "mimetype" }, "raw_contact_id=?", new String[] { id }, null); while (dataCursor.moveToNext()) { String data = dataCursor.getString(0); String mimetype = dataCursor.getString(1); System.out.println("data:" + data); System.out.println("mimetype:" + mimetype); } dataCursor.close(); System.out.println("----------"); } } cursor.close(); }
写联系人代码
public void click(View view) { String name = et_name.getText().toString().trim(); String phone = et_phone.getText().toString().trim(); String email = et_email.getText().toString().trim(); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone)) { Toast.makeText(this, "姓名或者电话不能为空", 1).show(); return; } // 把数据写入到系统的联系人. ContentResolver resolver = this.getContentResolver(); // ----------在raw_contant表中添加一条新的id--------------- Uri uri = Uri.parse("content://com.android.contacts/raw_contacts"); // 插入联系人 必须要知道 新的联系人的id Cursor cursor = resolver.query(uri, new String[] { "contact_id" }, null, null, "contact_id"); int contact_id; if (cursor.moveToLast()) { contact_id = cursor.getInt(0) + 1; // 数据库里面有数据 最后一条联系人的id + 1 } else {// 原先数据库是空的 从第一个联系人开始 contact_id = 1; } ContentValues values = new ContentValues(); values.put("contact_id", contact_id); resolver.insert(uri, values); // ----------------------------- // ------------在data表里面 添加id对应的数据------------- Uri dataUri = Uri.parse("content://com.android.contacts/data"); // 插入姓名 ContentValues nameValue = new ContentValues(); nameValue.put("data1", name); nameValue.put("raw_contact_id", contact_id); nameValue.put("mimetype", "vnd.android.cursor.item/name"); resolver.insert(dataUri, nameValue); // 插入电话 ContentValues phoneValue = new ContentValues(); phoneValue.put("data1", phone); phoneValue.put("raw_contact_id", contact_id); phoneValue.put("mimetype", "vnd.android.cursor.item/phone_v2"); resolver.insert(dataUri, phoneValue); // 插入邮箱 if (!TextUtils.isEmpty(email)) { ContentValues emailValue = new ContentValues(); emailValue.put("data1", email); emailValue.put("raw_contact_id", contact_id); emailValue.put("mimetype", "vnd.android.cursor.item/email_v2"); resolver.insert(dataUri, emailValue); } Toast.makeText(this, "插入数据成功", 0).show(); }