跨程序共享数据

一、内容提供器

内容提供器(Content Provider)主要用于在不同的应用程序之间实现数据共享的功能,它提供了一套完整的机制,允许一个程序访问另一个程序中的数据,同时还能保证被访数据的安全性。

内容提供器的用法一般有两种,一种是使用现有的内容提供器来读取和操作相应程序中的数据,另一种是创建自己的内容提供器给我们程序的数据提供外部访问接口。

二、ContentResolver 的基本用法

对于每一个应用程序来说,如果想要访问内容提供器中共享的数据,就一定要借助ContentResolve 类,可以通过Context 中的getContentResolver()方法获取到该类的实例。ContentResolver 中提供了一系列的方法用于对数据进行CRUD 操作,其中insert()方法用于添加数据,update()方法用于更新数据,delete()方法用于删除数据,query()方法用于查询数据。

三、读取系统联系人

读取系统联系人也是需要声明权限的,因此修改AndroidManifest.xml 中的代码:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contactstest"
android:versionCode="1"
android:versionName="1.0" >
……
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
…… </manifest>

读联系人函数

    private void readContacts(){
        Cursor cursor=null;
        try {
            cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, 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));
                contactsList.add(displayName+"\n"+number);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }finally{
            if(cursor!=null){
                cursor.close();
            }
        }
    }

通过读到的联系人,添加点击事件,直接跳转到拨打界面,实现拨打电话功能(注意注册权限):

     contactsView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
                // TODO Auto-generated method stub
                //获得字符串是姓名+换行+电话号码
                String contactInfo=contactsList.get(position);
                String contact=contactInfo.substring(contactInfo.indexOf("\n")+1);
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+contact));
                startActivity(intent);
            }
        });

 总结:

Cursor:

  • Cursor 是每行的集合。
  • 使用 moveToFirst() 定位第一行。
  • 你必须知道每一列的名称。
  • 你必须知道每一列的数据类型。
  • Cursor 是一个随机的数据源。
  • 所有的数据都是通过下标取得。
posted @ 2016-03-16 18:07  好人难寻  阅读(369)  评论(0编辑  收藏  举报