Android读写联系人数据(内容提供者应用)

2024-06-11 18:58

本文主要是介绍Android读写联系人数据(内容提供者应用),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

转载

先加二个读和写权限:

<uses-permission android:name="android.permission.READ_CONTACTS" />

<uses-permission android:name="android.permission.WRITE_CONTACTS" />  

 

复制代码
package com.eboy.test;

import java.util.ArrayList;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.util.Log;

public  class ContectTest  extends AndroidTestCase {
    
     private  static  final String TAG = "TestContact";
    
     // 查询所有联系人的姓名,电话,邮箱
     public  void TestContact()  throws Exception {        
        Uri uri = Uri.parse("content://com.android.contacts/contacts");
        ContentResolver resolver = getContext().getContentResolver();
        Cursor cursor = resolver.query(uri,  new String[]{"_id"},  nullnullnull);
         while (cursor.moveToNext()) {
             int contractID = cursor.getInt(0);
            StringBuilder sb =  new StringBuilder("contractID=");
            sb.append(contractID);
            uri = Uri.parse("content://com.android.contacts/contacts/" + contractID + "/data");
            Cursor cursor1 = resolver.query(uri,  new String[]{"mimetype", "data1", "data2"},  nullnullnull);
             while (cursor1.moveToNext()) {
                String data1 = cursor1.getString(cursor1.getColumnIndex("data1"));
                String mimeType = cursor1.getString(cursor1.getColumnIndex("mimetype"));
                 if ("vnd.android.cursor.item/name".equals(mimeType)) {  // 是姓名
                    sb.append(",name=" + data1);
                }  else  if ("vnd.android.cursor.item/email_v2".equals(mimeType)) {  // 邮箱
                    sb.append(",email=" + data1);
                }  else  if ("vnd.android.cursor.item/phone_v2".equals(mimeType)) {  // 手机
                    sb.append(",phone=" + data1);
                }                
            }
            cursor1.close();
            Log.i(TAG, sb.toString());
        }
        cursor.close();
    }
    
     // 查询指定电话的联系人姓名,邮箱
     public  void testContactNameByNumber()  throws Exception {
        String number = "18052369652";
        Uri uri = Uri.parse("content://com.android.contacts/data/phones/filter/" + number);
        ContentResolver resolver = getContext().getContentResolver();
        Cursor cursor = resolver.query(uri,  new String[]{"display_name"},  nullnullnull);
         if (cursor.moveToFirst()) {
            String name = cursor.getString(0);
            Log.i(TAG, name);
        }
        cursor.close();
    }
    
     // 添加联系人,使用事务
     public  void testAddContact()  throws Exception {
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = getContext().getContentResolver();
        ArrayList<ContentProviderOperation> operations =  new ArrayList<ContentProviderOperation>();
        ContentProviderOperation op1 = ContentProviderOperation.newInsert(uri)
            .withValue("account_name",  null)
            .build();
        operations.add(op1);
        
        uri = Uri.parse("content://com.android.contacts/data");
        ContentProviderOperation op2 = ContentProviderOperation.newInsert(uri)
            .withValueBackReference("raw_contact_id", 0)
            .withValue("mimetype", "vnd.android.cursor.item/name")
            .withValue("data2", "龚小永")
            .build();
        operations.add(op2);
        
        ContentProviderOperation op3 = ContentProviderOperation.newInsert(uri)
            .withValueBackReference("raw_contact_id", 0)
            .withValue("mimetype", "vnd.android.cursor.item/phone_v2")
            .withValue("data1", "13539777967")            
            .withValue("data2", "2")
            .build();
        operations.add(op3);
        
        ContentProviderOperation op4 = ContentProviderOperation.newInsert(uri)
        .withValueBackReference("raw_contact_id", 0)
        .withValue("mimetype", "vnd.android.cursor.item/email_v2")
        .withValue("data1", "asdfasfad@163.com")            
        .withValue("data2", "2")
        .build();
    operations.add(op4);
        
        resolver.applyBatch("com.android.contacts", operations);
    }
    
复制代码


/Files/jxgxy/ReadWriteContact.rar

转载:Android读写联系人数据(内容提供者应用) 

布局文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
     xmlns:tools = "http://schemas.android.com/tools"
     android:id = "@+id/ll"
     android:layout_width = "match_parent"
     android:layout_height = "match_parent"
     android:orientation = "vertical"
     android:paddingBottom = "@dimen/activity_vertical_margin"
     android:paddingLeft = "@dimen/activity_horizontal_margin"
     android:paddingRight = "@dimen/activity_horizontal_margin"
     android:paddingTop = "@dimen/activity_vertical_margin"
     tools:context = ".MainActivity" >
     < LinearLayout
         android:layout_width = "match_parent"
         android:layout_height = "wrap_content" >
         < Button
             android:id = "@+id/btn_getcontacts"
             android:layout_width = "0dp"
             android:layout_height = "wrap_content"
             android:onClick = "read_click"
             android:layout_weight = "1"
             android:text = "读取联系人" />
         < Button
             android:id = "@+id/btn_insertcontact"
             android:layout_width = "0dp"
             android:layout_height = "wrap_content"
             android:onClick = "insert_click"
             android:layout_weight = "1"
             android:text = "写入联系人" />
     </ LinearLayout >
</ LinearLayout >

核心Activity 两种方式:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package com.example.readcontacts;
import java.util.ArrayList;
import java.util.List;
import com.pas.domain.ContactModel;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity  extends Activity
{
     LinearLayout ll;
     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         ll = (LinearLayout) findViewById(R.id.ll);
     }
     @Override
     public boolean onCreateOptionsMenu(Menu menu)
     {
         // Inflate the menu; this adds items to the action bar if it is present.
         getMenuInflater().inflate(R.menu.main, menu);
         return true ;
     }
     public void read_click(View view)
     {
         getContactList();
     }
     public void insert_click(View view)
     {
         addContact();
         Toast.makeText( this "添加成功" , Toast.LENGTH_LONG).show();
     }
     private void addContact()
     {
         ContentResolver resolver = getContentResolver();
         ArrayList<ContentProviderOperation> operations= new ArrayList<ContentProviderOperation>();
         
         Uri raw_contacts_uri = Uri.parse( "content://com.android.contacts/raw_contacts" );
         Uri data_uri = Uri.parse( "content://com.android.contacts/data" );
         
         ContentProviderOperation op1=ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                 .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null )
                 .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null ).build();
         operations.add(op1);
         
         ContentProviderOperation op2=ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,  0 )
                 .withValue(ContactsContract.Data.MIMETYPE,
                         ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                 .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,  "王刚" )
                 .build();
         operations.add(op2);
         
         ContentProviderOperation op3=ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,  0 )
                 .withValue(ContactsContract.Data.MIMETYPE,
                         ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                 .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,  "990009" )
                 .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
                 .build();
         
         operations.add(op3);
         
         ContentProviderOperation op4=ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,  0 )
                 .withValue(ContactsContract.Data.MIMETYPE,
                         ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                 .withValue(ContactsContract.CommonDataKinds.Email.DATA,  "ping@12.com" )
                 .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM)
                 .build();
         operations.add(op4);
         
         try
             resolver.applyBatch(ContactsContract.AUTHORITY, operations); 
         catch (Exception e) { 
             e.printStackTrace();
        
         
//      ContentValues raw_values = new ContentValues();
//
//      Cursor cursor = resolver.query(raw_contacts_uri, new String[]
//      { "_id" }, null, null, null);
//      cursor.moveToLast();
//      int lastid = cursor.getInt(0);
//      int newid = lastid + 1;
//
//      raw_values.put("contact_id", newid);
//      resolver.insert(raw_contacts_uri, raw_values);
//
//      // 电话插入
//      ContentValues phonevalues = new ContentValues();
//      phonevalues.put("data1", "898989");
//      phonevalues.put("mimetype", "vnd.android.cursor.item/phone_v2");
//      phonevalues.put("raw_contact_id", newid);
//      resolver.insert(data_uri, phonevalues);
//
//      // email插入
//      ContentValues emailvalues = new ContentValues();
//      emailvalues.put("data1", "ping@126.com");
//      emailvalues.put("mimetype", "vnd.android.cursor.item/email_v2");
//      emailvalues.put("raw_contact_id", newid);
//      resolver.insert(data_uri, emailvalues);
//
//      // name插入
//      ContentValues namevalues = new ContentValues();
//      namevalues.put("data1", "王刚");
//      namevalues.put("mimetype", "vnd.android.cursor.item/name");
//      namevalues.put("raw_contact_id", newid);
//      resolver.insert(data_uri, namevalues);
     }
     private void getContactList()
     {
         ContentResolver resolver = getContentResolver();
         Uri raw_contacts_uri = Uri.parse( "content://com.android.contacts/raw_contacts" );
         Uri data_uri = Uri.parse( "content://com.android.contacts/data" );
         ll.removeAllViews();
         Cursor cursor = resolver.query(raw_contacts_uri,  null null null null );
         while (cursor.moveToNext())
         {
             String contactid = cursor.getString(cursor.getColumnIndex( "contact_id" ));
             System.out.println(contactid +  "\n" );
             if ( null != contactid)
             {
                 StringBuffer sb =  new StringBuffer( "联系人ID:" );
                 sb.append(contactid).append( " " );
                 Cursor data_cursor = resolver.query(data_uri,  null "raw_contact_id=?" new String[]
                 { contactid },  null );
                 while (data_cursor.moveToNext())
                 {
                     String data1 = data_cursor.getString(data_cursor.getColumnIndex( "data1" ));
                     String mimetype = data_cursor.getString(data_cursor.getColumnIndex( "mimetype" ));
                     System.out.println( "mimetype=" + mimetype +  ";data1=" + data1);
                     sb.append(data1).append( " " );
                 }
                 data_cursor.close();
                 TextView tv =  new TextView( this );
                 LinearLayout.LayoutParams lp =  new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                 tv.setLayoutParams(lp);
                 tv.setText(sb.toString());
                 ll.addView(tv);
             }
         }
         cursor.close();
     }
}

这篇关于Android读写联系人数据(内容提供者应用)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1052009

相关文章

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

Pandas统计每行数据中的空值的方法示例

《Pandas统计每行数据中的空值的方法示例》处理缺失数据(NaN值)是一个非常常见的问题,本文主要介绍了Pandas统计每行数据中的空值的方法示例,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是空值?为什么要统计空值?准备工作创建示例数据统计每行空值数量进一步分析www.chinasem.cn处

C语言中位操作的实际应用举例

《C语言中位操作的实际应用举例》:本文主要介绍C语言中位操作的实际应用,总结了位操作的使用场景,并指出了需要注意的问题,如可读性、平台依赖性和溢出风险,文中通过代码介绍的非常详细,需要的朋友可以参... 目录1. 嵌入式系统与硬件寄存器操作2. 网络协议解析3. 图像处理与颜色编码4. 高效处理布尔标志集合

如何使用 Python 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

Spring 请求之传递 JSON 数据的操作方法

《Spring请求之传递JSON数据的操作方法》JSON就是一种数据格式,有自己的格式和语法,使用文本表示一个对象或数组的信息,因此JSON本质是字符串,主要负责在不同的语言中数据传递和交换,这... 目录jsON 概念JSON 语法JSON 的语法JSON 的两种结构JSON 字符串和 Java 对象互转

C++如何通过Qt反射机制实现数据类序列化

《C++如何通过Qt反射机制实现数据类序列化》在C++工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作,所以本文就来聊聊C++如何通过Qt反射机制实现数据类序列化吧... 目录设计预期设计思路代码实现使用方法在 C++ 工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作。由于数据类

Android实现在线预览office文档的示例详解

《Android实现在线预览office文档的示例详解》在移动端展示在线Office文档(如Word、Excel、PPT)是一项常见需求,这篇文章为大家重点介绍了两种方案的实现方法,希望对大家有一定的... 目录一、项目概述二、相关技术知识三、实现思路3.1 方案一:WebView + Office Onl