Android开发 ContentResolver,ContentProvider的使用方法

ContentResolver之前在介绍联系人的时候已经用过了,用于查询另一个程序的数据库,相对的,而ContentProvider就是把自己的数据库提供给其他程序查询。 ChatDataProvider:

package com.pocketdigi.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import com.pocketdigi.db.DatabaseHelper;


public class ChatDataProvider extends ContentProvider {


    @Override
    public boolean onCreate() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        // TODO Auto-generated method stub
        //查询未读总数
        UriMatcher  sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        Cursor cursor=null;
        //查询未读,匹配URI  content://com.pocketdigi.provider/unread
        sMatcher.addURI("com.pocketdigi.provider", "unread", 1);
        switch(sMatcher.match(uri))
        {
        case 1:
            DatabaseHelper dbHelper=new DatabaseHelper(    this.getContext());
            SQLiteDatabase db=dbHelper.getWritableDatabase();
            cursor= db.rawQuery("select count(*) as count from message where readed=0;",null);
            break;
        }

        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

}

功能简单,只能查询未读的消息数量,所以query里很多参数都忽略了,各个参数可以参考db.query的参数列表。 AndroidManifest.xml里注册Provider:

<provider
    android:name="com.pocketdigi.provider.ChatDataProvider"
    android:authorities="com.pocketdigi.provider" >
</provider>

另一个程序中的使用方法:

ContentResolver resolver=getContentResolver();
        Uri uri=Uri.parse("content://com.pocketdigi.provider/unread");
        Cursor cursor=resolver.query(uri, null, null, null, null);
        if(cursor!=null)
        {
            cursor.moveToFirst();
            int count=cursor.getInt(0);
            updateUnReadCountUI(count);
        }