失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > android 使用内容提供者获取手机联系人

android 使用内容提供者获取手机联系人

时间:2020-03-07 20:18:01

相关推荐

android 使用内容提供者获取手机联系人

最近在学习安卓的相关内容, 正好在写获取手机联系人的程序, 就想到了内容提供者, 这里有几点需要注意, 写到这里, 以后方便自己查询。

1. 手机联系人的数据库是存储在 data/data/com.android.providers.contacts/database下

contact2.db的, 利用sqlite3 打开数据库, 我们可以方便的看到我们需要的几张表, raw_contact, contact, data, mimetype表

2. 分析表格我们知道 mimetype 决定了后面的data1 所表示内容, 我们只需要根据 raw_contact_id, 提取相应记录的 mimetype, data1, 即可获取我们需要的联系人的信息了。

3. 网上的很多方法, 都是直接写 “ content://com.android.contacts/data” , 来解析uri, 个人不太喜欢这种方式, 于是查了下sdk, 使用Data.content_uri, 实质是一样的, 这里做个说明。

4. 下面的代码,getContactData, 主要用来获取手机联系人的姓名和电话号码, 基本思想在 (2) 中阐述了, onCreate中 使用 simpleAdapter, 将获取的联系人数据填入到相应的控件位置中去。

5. 安卓环境为 android4.2.2, 界面显示有些丑陋, 不过我已经尽力了<-_->!!

6. 运行效果:

public class Setup3ActivitySelectContact extends Activity {private static final String TAG = "Setup3ActivitySelectContact";private ListView lv_contacts;protected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_safe_setup3_contacts);lv_contacts = (ListView) findViewById(R.id.lv_contacts);List<Map<String,String>> data = getContactsData();ListAdapter adapter = new SimpleAdapter(this, data,R.layout.activity_safe_setup3_contacts_item,new String[]{"name", "phone"},new int[]{R.id.name, R.id.phone});lv_contacts.setAdapter(adapter);}private List<Map<String, String>> getContactsData() {// TODO Auto-generated method stubContentResolver resolver = getContentResolver();// get the raw_contact_idCursor cursor = resolver.query(RawContacts.CONTENT_URI, new String[]{RawContacts._ID}, null, null, null);List<Map<String, String>> list = new ArrayList();while (cursor.moveToNext()){//Log.d(TAG, cursor.getString(0));long id = cursor.getLong(0);Map<String, String> item = new HashMap();// base on the raw_contact_id select the data1 and mimetypeCursor cursor2 = resolver.query(Data.CONTENT_URI,new String[]{Data.DATA1, Data.MIMETYPE},Data.RAW_CONTACT_ID + "=?", new String[]{id + ""},null);while (cursor2.moveToNext()){String type = cursor2.getString(1);String data = cursor2.getString(0);if (CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(type)){item.put("name", data);}else if (CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(type)){item.put("phone", data);}}list.add(item);}return list;}}

如果觉得《android 使用内容提供者获取手机联系人》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。