Android基础知识梳理-四大组件之Content Provider

定义 ContentProvider顾名思义就是内容提供者,通过屏蔽底层进程间通信的具体实现,为不同应用之间的数据共享提供统一的接口。用户可以灵活的实现ContentProvider封装的数据存储和增删改查接口。

  • ContentProvider中使用URI访问数据,URI格式如下:
    [scheme://][host:port][path][?query]
    content://com.example.provider/person
使用 1.在AndroidManifest.xml注册

  • 其中authorities字段即为当前ContentProvider的唯一标识,访问URI为content://com.example.provider
2.代码实现
(1)定义数据库操作类
public class DbHelper extends SQLiteOpenHelper { private static final String DB_NAME = "person.db"; private static final int DB_VERSION = 1; private static final String TABLE_NAME = "person"; private static final String ID = "_id"; private static final String NAME = "name"; public DbHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" + "," + NAME + " CHAR(10) )"; db.execSQL(sql); }@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }

(2)实现ContentProvider
public class ExampleContentProvider extends ContentProvider { private SQLiteDatabase db; private static final String MAUTHORITIESNAME = "com.example.provider"; private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); private static final int PERSON = 1; private static final int PERSON_NUMBER = 2; private static final int PERSON_TEXT = 3; private static final String TABLE_NAME = "person"; // 构建URI static { // content://com.example.provider/person matcher.addURI(MAUTHORITIESNAME, "person", PERSON); // # 代表任意数字content://com.example.provider/person/1 matcher.addURI(MAUTHORITIESNAME, "person/#", PERSON_NUMBER); // * 代表任意文本 content://com.example.provider/person/filter/personXxx matcher.addURI(MAUTHORITIESNAME, "person/filter/*", PERSON_TEXT); }@Override public int delete(Uri uri, String selection, String[] selectionArgs) { // Implement this to handle requests to delete one or more rows. return 0; }@Override public String getType(Uri uri) { // Implement this to handle requests for the MIME type of the data // at the given URI. return null; }@Override public Uri insert(Uri uri, ContentValues values) { // Implement this to handle requests to insert a new row. int match = matcher.match(uri); switch (match) { case PERSON: long id = db.insert(TABLE_NAME, null, values); return ContentUris.withAppendedId(uri, id); case PERSON_NUMBER: case PERSON_TEXT: default: break; } return null; }@Override public boolean onCreate() { // Implement this to initialize your content provider on startup. DbHelper dbHelper = new DbHelper(getContext()); db = dbHelper.getWritableDatabase(); return true; }@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Implement this to handle query requests from clients. int match = matcher.match(uri); switch (match) { case PERSON: db.query(TABLE_NAME, projection, selection, selectionArgs, null ,null, sortOrder); case PERSON_NUMBER: case PERSON_TEXT: default: break; } return null; }@Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // Implement this to handle requests to update one or more rows. return 0; } }

(3)通过ContentResolver调用ContentProvider访问数据库
private String uri = "content://com.example.provider/person"; public String queryPersonName() { String name = null; Cursor cursor = getContentResolver().query(Uri.parse(uri), null, null, null, null); while (cursor.moveToNext()) { name = cursor.getString(cursor.getColumnIndex("name")); } return name; }public void insertPerson(String name) { ContentValues values = new ContentValues(); values.put("name", name); Uri result = getContentResolver().insert(Uri.parse(uri), values); long parseid = ContentUris.parseId(result); if (parseid > 0) { // insert success } }

内容处理者ContentResolver ContentResolver通过URI调用getContentResolver()获取ContentProvider 提供的数据接口,进而进行增删改查等操作。
getContentResolver().query(Uri.parse(uri), null, null, null, null);

内容观察者ContentObserver 【Android基础知识梳理-四大组件之Content Provider】ContentObserver 内容观察者通过指定URI 监听ContentProvider数据是否改变。
1.注册ContentObserver
private void registerContentObserver() { Uri uri = Uri.parse("content://com.example.provider/person"); getContentResolver().registerContentObserver(uri, true, new ExampleContentObserver(new Handler())); }

2.监听内容变化
public class ExampleContentObserver extends ContentObserver { private static final String TAG = ExampleContentObserver.class.getSimpleName(); public ExampleContentObserver(Handler handler) { super(handler); }@Override public void onChange(boolean selfChange) { super.onChange(selfChange); Log.i(TAG, "content has been changed"); } }

    推荐阅读