ContentResolver和ContentProvider是Android中用于實現(xiàn)數(shù)據(jù)共享和訪問的重要組件。
public class MyContentProvider extends ContentProvider {
private DBHelper dbHelper; // 數(shù)據(jù)庫幫助類
@Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query("table_name", projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
long id = db.insert("table_name", null, values);
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rows = db.update("table_name", values, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return rows;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rows = db.delete("table_name", selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return rows;
}
@Override
public String getType(Uri uri) {
return null;
}
}
在使用ContentResolver和ContentProvider時,需要先注冊ContentProvider并在AndroidManifest.xml中聲明權(quán)限和uri。然后可以通過ContentResolver來操作數(shù)據(jù),例如查詢、插入、更新、刪除等操作。
以上是ContentResolver和ContentProvider的基本使用方法,開發(fā)者可以根據(jù)具體的需求來進一步深入學習和使用。