标签:
MainActivity
public class MainActivity extends ListActivity {// 访问内容提供者时需要的主机名称public static final String authority = "com.bqt.contentprovider.person";private TextView tv_info;private ContentResolver resolver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);String[] array = { "获取所有数据", "插入一条name=bqt的数据", "修改name=bqt的数据", "删除name=bqt的数据", "清空所有数据",//"读取收件箱信息", "往收件箱插入一条信息", "读取手机联系人", "查询\"110\"的联系人信息", "添加一个新的联系人" };for (int i = 0; i < array.length; i++) {array[i] = i + "、" + array[i];}ListAdapter mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>(Arrays.asList(array)));resolver = getContentResolver();// 获取内容解析器tv_info = new TextView(this);// 将内容显示在TextView中tv_info.setTextColor(Color.BLUE);tv_info.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);tv_info.setPadding(20, 10, 20, 10);getListView().addFooterView(tv_info);setListAdapter(mAdapter);}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {Uri uri = null;Uri returnUri = null;StringBuffer sb = new StringBuffer();int num = 0;ContentValues values = new ContentValues();// 要修改或插入的数据switch (position) {case 0: // 获取所有数据uri = Uri.parse("content://" + authority + "/query");// 指定解析器要解析的路径。注意query前要加路径分隔符【/】Log.i("bqt", uri.toString());//【 content://com.bqt.contentprovider.person/query】Cursor cursor = resolver.query(uri, null, null, null, null);// 获取解析器解析的结果集if (cursor != null) {while (cursor.moveToNext()) {int uId = cursor.getInt(cursor.getColumnIndex("id"));// 取出需要的内容String uName = cursor.getString(cursor.getColumnIndex("name"));String uNumber = cursor.getString(cursor.getColumnIndex("number"));sb.append("id:" + uId + " name:" + uName + " number:" + uNumber + "\n");}tv_info.setText(sb.toString());cursor.close();}break;case 1:// 插入一条数据uri = Uri.parse("content://" + authority + "/insert");values.put("id", new Random().nextInt(10));values.put("name", "bqt");values.put("number", "10086");returnUri = resolver.insert(uri, values);tv_info.setText("插入信息的uri:" + returnUri.toString());break;case 2: // 修改一条数据uri = Uri.parse("content://" + authority + "/update");values.put("name", "dog");values.put("number", "10087");num = resolver.update(uri, values, "name=?", new String[] { "bqt" });// 指定uri,values,Where子句,占位符的值tv_info.setText("修改信息个数:" + num);break;case 3: // 删除一条数据uri = Uri.parse("content://" + authority + "/delete");num = resolver.delete(uri, "name=?", new String[] { "bqt" });tv_info.setText("删除信息个数:" + num);break;case 4: // 清空,删除所有数据uri = Uri.parse("content://" + authority + "/delete");num = resolver.delete(uri, null, null);tv_info.setText("删除信息个数:" + num);break;//******************************************************************************************case 5: // 读取收件箱信息readMsgs();break;case 6: // 往收件箱插入一条信息insertMsg();break;case 7: // 读取手机联系人readContact();break;case 8: // 查询指定电话的联系人信息queryContact("110");break;case 9: // 添加一个新的联系人writeContact();break;}}/** 读取收件箱信息。<uses-permission android:name="android.permission.READ_SMS"/> */public void readMsgs() {Uri uri = Uri.parse("content://sms/");ContentResolver resolver = getContentResolver();//获取的是哪些列的信息Cursor cursor = resolver.query(uri, new String[] { "address", "date", "type", "body" }, null, null, null);if (cursor != null) {StringBuffer sb = new StringBuffer();while (cursor.moveToNext()) {sb.append("联系人:" + cursor.getString(cursor.getColumnIndex("address")));sb.append("\n时间:" + cursor.getString(cursor.getColumnIndex("date")));sb.append("\n类型:" + cursor.getString(cursor.getColumnIndex("type")));sb.append("\n内容:" + cursor.getString(cursor.getColumnIndex("body")));sb.append("\n===============================\n");}tv_info.setText(sb.toString());cursor.close();}}/**读取手机收件箱,返回一个集合*/public ArrayList<String> getSms() {ArrayList<String> mArrayList = new ArrayList<String>();ContentResolver resolver = getContentResolver();Uri uri = Uri.parse("content://sms/");Cursor cursor = resolver.query(uri, new String[] { "body", "address", "type", "date" }, null, null, null);SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());while (cursor.moveToNext()) {String body = "内容:" + cursor.getString(0);String address = "联系人:" + cursor.getString(1);String type = "类型:" + cursor.getString(2);//1是接收到的,2是已发出 ,但是 3 是什么鬼?String date = "时间:" + formatter.format(new Date(Long.parseLong(cursor.getString(3))));mArrayList.add(new String(body + "\n" + address + "\n" + type + "\n" + date + "\n\n"));}cursor.close();return mArrayList;}/** 往收件箱插入一条信息,"android.permission.WRITE_SMS" 。从5.0开始,默认短信应用外的软件不能以写入短信数据库的形式发短信 */public void insertMsg() {ContentValues values = new ContentValues();values.put("address", "10086");//联系人values.put("type", 1);//类型1是"收到"的短信values.put("date", System.currentTimeMillis());//收到的时间values.put("body", "您的余额还有1,000,000万元!");//内容Uri returnUri = resolver.insert(Uri.parse("content://sms"), values);if (returnUri != null) {tv_info.setText(returnUri.toString());if (returnUri.getPath().equals("/0")) {Toast.makeText(this, "添加失败:" + returnUri.getPath(), Toast.LENGTH_SHORT).show();} else {Toast.makeText(this, "添加成功:" + returnUri.getPath(), Toast.LENGTH_SHORT).show();}}}/** 读取手机联系人 <uses-permission android:name="android.permission.READ_CONTACTS"/> */public void readContact() {//查询raw_contacts表获得联系人的idContentResolver resolver = getContentResolver();Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;//查询联系人数据Cursor cursor = resolver.query(uri, null, null, null, null);if (cursor != null) {StringBuffer sb = new StringBuffer();while (cursor.moveToNext()) {sb.append("姓名:" + cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));sb.append("\n号码:" + cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));sb.append("\n===============================\n");}tv_info.setText(sb.toString());cursor.close();}cursor.close();}/**查询指定电话的联系人信息*/public void queryContact(String number) {Uri uri = Uri.parse("content://com.android.contacts/data/phones/filter/" + number);ContentResolver resolver = getContentResolver();Cursor cursor = resolver.query(uri, new String[] { "display_name" }, null, null, null);if (cursor != null) {if (cursor.moveToFirst()) {String name = cursor.getString(0);Toast.makeText(this, number + "对应的联系人名称:" + name, Toast.LENGTH_SHORT).show();} else {Toast.makeText(this, number + "木有此联系人", Toast.LENGTH_SHORT).show();}cursor.close();}}/**读取手机联系人,返回一个集合*/public List<Map<String, String>> getContacts() {//把所有的联系人保存在List集合中List<Map<String, String>> list = new ArrayList<Map<String, String>>();ContentResolver resolver = getContentResolver();Uri uriId = Uri.parse("content://com.android.contacts/raw_contacts");//id信息Uri uriData = Uri.parse("content://com.android.contacts/data");//具体的联系人信息//获取包含id的结果集Cursor cursor = resolver.query(uriId, new String[] { "contact_id" }, null, null, null);//遍历此包含id的结果集while (cursor.moveToNext()) {String contact_id = cursor.getString(0);if (contact_id != null) {//将对应此id的所有联系人信息保存在map集合中Map<String, String> map = new HashMap<String, String>();Cursor dataCursor = resolver.query(uriData, new String[] { "data1", "mimetype" }, "contact_id=?", new String[] { contact_id }, null);//遍历对应此id的所有联系人信息的结果集while (dataCursor.moveToNext()) {String data1 = dataCursor.getString(0);//联系人信息String mimetype = dataCursor.getString(1);//此联系人信息的类型//若mimetype为联系人的姓名或电话号码,则以相应的格式保存在map集合中if ("vnd.android.cursor.item/name".equals(mimetype)) map.put("name", data1);//保存姓名else if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) map.put("phone", data1);//保存电话}//将map集合中的数据保存在list集合中list.add(map);dataCursor.close();}}cursor.close();return list;}/**添加一个新的联系人。"android.permission.WRITE_CONTACTS" */public void writeContact() {ContentResolver resolver = getContentResolver();Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");//保存联系人的idUri dataUri = Uri.parse("content://com.android.contacts/data");//保存联系人的数据Cursor cursor = resolver.query(uri, new String[] { "_id" }, null, null, null);// 注意列名是【_id】if (cursor.moveToLast()) {// 移动到最后一条记录int lastId = cursor.getInt(0);// 获取最后一条记录【第零列】的值(即id的值)int newId = lastId + 1;// 设定要插入的记录的id值ContentValues values = new ContentValues();values.put("contact_id", newId);//插入一条记录resolver.insert(uri, values);// 向raw_contacts表中插入一条记录//电话ContentValues phoneValues = new ContentValues();phoneValues.put("data1", "110");//向data1表中插入一条指定的值(电话)phoneValues.put("mimetype", "vnd.android.cursor.item/phone_v2");//指定这个值是一个电话类型phoneValues.put("raw_contact_id", newId);//指定这个值(电话)对应哪个idresolver.insert(dataUri, phoneValues);//emaiContentValues emaiValues = new ContentValues();emaiValues.put("data1", "bqt@qq.com");emaiValues.put("mimetype", "vnd.android.cursor.item/email_v2");emaiValues.put("raw_contact_id", newId);resolver.insert(dataUri, emaiValues);//姓名ContentValues nameValues = new ContentValues();nameValues.put("data1", "包青天");nameValues.put("mimetype", "vnd.android.cursor.item/name");nameValues.put("raw_contact_id", newId);resolver.insert(dataUri, nameValues);}cursor.close();Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();}}
清单文件
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.bqt.contentresolver"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="21" /><uses-permission android:name="android.permission.READ_SMS" /><uses-permission android:name="android.permission.WRITE_SMS" /><uses-permission android:name="android.permission.READ_CONTACTS" /><uses-permission android:name="android.permission.WRITE_CONTACTS" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><!-- 内容提供者定义的权限 --><uses-permission android:name="com.bqt.permission" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name=".MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>
内容提供者 ContentResolver 数据库 示例 -2
标签:
原文地址:http://www.cnblogs.com/baiqiantao/p/5535471.html