这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录 前一修订版 后一修订版 | 前一修订版 | ||
wiki:book:notes:android:第一行代码-android-第2版-郭霖:第7章 [2022/04/06 19:43] 博丽幻月 [todo] |
wiki:book:notes:android:第一行代码-android-第2版-郭霖:第7章 [2022/04/07 14:39] (当前版本) 博丽幻月 [创建自己的内容提供器] |
||
---|---|---|---|
行 1: | 行 1: | ||
====== 第7章 跨程序共享数据——探究内容提供器 ====== | ====== 第7章 跨程序共享数据——探究内容提供器 ====== | ||
===== 简介 ===== | ===== 简介 ===== | ||
- | 内容提供其(Content Provider):在不同应用程序之间,实现数据共享的功能。允许一个程序访问另一个程序的数据,还能保证被访问数据的安全性。\\ | + | 内容提供器(Content Provider):在不同应用程序之间,实现数据共享的功能。允许一个程序访问另一个程序的数据,还能保证被访问数据的安全性。\\ |
===== 运行时权限 ===== | ===== 运行时权限 ===== | ||
==== 在程序运行时申请权限 ==== | ==== 在程序运行时申请权限 ==== | ||
行 42: | 行 42: | ||
} | } | ||
</ | </ | ||
+ | ===== 访问其他程序中的数据 ===== | ||
+ | ==== ContentResolver的基本用法 ==== | ||
+ | **内容URI格式**\\ | ||
+ | '' | ||
+ | **解析成Uri对象**\\ | ||
+ | <code java> | ||
+ | Uri uri = Uri.parse(" | ||
+ | </ | ||
+ | === query() === | ||
+ | <code java> | ||
+ | Cursor cursor = getContentResolver().query(uri, | ||
+ | </ | ||
+ | 查询完后进行遍历\\ | ||
+ | <code java> | ||
+ | if (cursor != null) { | ||
+ | while (cursor.moveToNext()) { | ||
+ | String column1 = cursor.getString(cursor.getColumnIndex(" | ||
+ | int column2 = cursor.getInt(cursor.getColumnIndex(" | ||
+ | } | ||
+ | cursor.close(); | ||
+ | } | ||
+ | </ | ||
+ | === insert() === | ||
+ | <code java> | ||
+ | ContentValues values= new ContentValues(); | ||
+ | values.put(" | ||
+ | values.put(" | ||
+ | getContentResolver().insert(uri, | ||
+ | </ | ||
+ | === update() === | ||
+ | <code java> | ||
+ | ContentValues values = new ContentValues(); | ||
+ | values.put(" | ||
+ | getContentResolver().update(uri, | ||
+ | </ | ||
+ | === delete() === | ||
+ | <code java> | ||
+ | getContentResolver().delete(uri, | ||
+ | </ | ||
+ | ==== 读取系统联系人 ==== | ||
+ | 读取联系人方法:\\ | ||
+ | <code java> | ||
+ | private void readContacts() { | ||
+ | Cursor cursor = null; | ||
+ | try { | ||
+ | // 查询联系人数据 | ||
+ | cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, | ||
+ | if(cursor != null) { | ||
+ | while (cursor.moveToNext()) { | ||
+ | // | ||
+ | String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); | ||
+ | // | ||
+ | String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); | ||
+ | } | ||
+ | } | ||
+ | } catch (Exception e) { | ||
+ | e.printStackTrace(); | ||
+ | } finally { | ||
+ | if (cursor != null) { | ||
+ | cursor.close(); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | 判断是否有权限和读取:\\ | ||
+ | <code java> | ||
+ | if(ContextCompat.checkSelfPermission(this, | ||
+ | ActivityCompat.requestPermissions(this, | ||
+ | } else { | ||
+ | readContacts(); | ||
+ | } | ||
+ | </ | ||
+ | ===== 创建自己的内容提供器 ===== | ||
+ | ==== 创建内容提供器步骤 ==== | ||
+ | **TBD**\\ |