Android笔记(五十五) Android四大组件之一——ContentProvider,使用系统提供的ContentProvider

      因为在Android中,存储系统联系人姓名和电话是存在与不同的ContentProvider中的,具体如何查找,可以从Android的源代码中查看,在android.providers包中列出了所有系统已经封装好的ContentProvider,譬如我们要查看联系人相关的,就去ContactsContract当中去寻找相关信息,要查看短信相关的,就去Telephony中寻找相关信息。

  

 

      查找系统联系人

MainActivity.java

package cn.lixyz.readcontacts;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button button;
    private static final Uri CONTACTS_URI = ContactsContract.Contacts.CONTENT_URI;
    private static final Uri PHONE_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new MyOnClickListener());

    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.button) {
                ContentResolver cr = getContentResolver();
                Cursor cursor = cr.query(CONTACTS_URI, new String[] { "_id", "display_name" }, null, null, null);
                if (cursor != null) {
                    List<String> phoneList = new ArrayList<String>();
                    cursor.moveToFirst();
                    do {
                        String name = cursor.getString(cursor.getColumnIndex("display_name"));
                        String id = cursor.getString(cursor.getColumnIndex("_id"));

                        Cursor c = cr.query(PHONE_URI, new String[] { "data1" }, "name_raw_contact_id=?",
                                new String[] { id }, null);
                        c.moveToFirst();
                        do {
                            Log.d("TTTT", "姓名:" + name + ",电话=" + c.getString(c.getColumnIndex("data1")));
                        } while (c.moveToNext());
                    } while (cursor.moveToNext());
                }
                cursor.close();

            }

        }

    }
}

 

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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="cn.lixyz.readsmstest.MainActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点我读取联系人" />

</LinearLayout>

在AndroidManifest.xml文件中添加读取联系人的权限

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

  运行结果:

  读取短信息:

MainActivity.java

package cn.lixyz.readsmstest;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Telephony.Sms;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ContentResolver cr = getContentResolver();
                Uri uri = Sms.CONTENT_URI;
                Cursor cursor = cr.query(uri, new String[] { "date", "body" }, null, null, null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        String date = cursor.getString(cursor.getColumnIndex("date"));
                        String body = cursor.getString(cursor.getColumnIndex("body"));

                        Date d = new Date(Long.valueOf(date));
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String dateStr = dateFormat.format(d);

                        Log.d("TTTT", "时间:" + dateStr + ",内容:" + body);

                    }
                }
                cursor.close();
            }
        });
    }
}

 

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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="cn.lixyz.readsmstest.MainActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点我读取短信" />

</LinearLayout>

 

在AndroidManifest.xml文件中添加读取短信的权限

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

插入联系人:

MainActivity.java

package cn.lixyz.writecontacts;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button button;
    public static final Uri CONTACTS_URI = ContactsContract.Contacts.CONTENT_URI;
    public static final Uri Phone_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                ContentValues values = new ContentValues();
                // 首先向RawContacts.CONTENT_URI执行一个空值插入(raw_contacts 表),
                // 为了获取生成的联系人 ID
                Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);
                // 然后获取系统返回的rawContactId , 就是新加入的这个联系人的 ID
                long rawContactId = ContentUris.parseId(rawContactUri);
                /*
                 * Andorid 中,将联系人的姓名、电话、分别存放在 data 表的同一个字段的两条记录当中 因此要 Insert 两次
                 */
                // 往data表入姓名数据
                values.clear();
                // raw_contacts_id 字段,是 raw_contacts表id 的外键,用于说明此记录属于哪一个联系人
                values.put(Data.RAW_CONTACT_ID, rawContactId);
                // mimitype_id 字段,用于描述此数据的类型,电话号码?Email?....
                values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); // 注意查看第二个参数的常量值
                values.put(StructuredName.GIVEN_NAME, "肆肆肆"); // 这个名字真好听
                getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
                // 往data表入电话数据
                values.clear();
                values.put(Data.RAW_CONTACT_ID, rawContactId);

                values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
                values.put(Phone.NUMBER, "444444444");
                values.put(Phone.TYPE, Phone.TYPE_MOBILE);
                getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
            }
        });
    }
}

 

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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="cn.lixyz.writecontacts.MainActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

在AndroidManifest.xml中添加写入联系人的权限

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

 

posted @ 2015-11-11 01:46  li-xyz  阅读(388)  评论(0编辑  收藏  举报