标签:
内容提供
public class PersonContentProvider extends ContentProvider{
private static final String AUTHORITY = "com.itheima28.sqlitedemo.providers.PersonContentProvider";
private static final int PRESON_INSERT_CODE = 0; // 操作person表添加的操作的uri匹配码
UriMatcher uriMatcher;
private PersonSQLiteOpenHelper mOpenHelper;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "person/insert", PRESON_INSERT_CODE);
}
@Override
public boolean onCreate() {
mOpenHelper = new PersonSQLiteOpenHelper(getContext());
return true;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
switch (uriMatcher.match(uri)) {
case PRESON_INSERT_CODE: // 添加人到person表中
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
if(db.isOpen()) {
long id = db.insert("person", null, values);
db.close();
return ContentUris.withAppendedId(uri, id);
}
break;
default:
throw new IllegalArgumentException("uri不匹配: " + uri);
}
return null;
}
}
UriMatcher
内容访问
ContentResolver resolver = getContext().getContentResolver();
uri = resolver.insert(uri, values);
int count = resolver.delete(uri, where, selectionArgs);
int count = resolver.update(uri, values, "_id = ?", new String[]{"20"});
Cursor cursor = resolver.query(uri, new String[]{"_id", "name", "age"}, null, null, "_id desc");
内容监听
resolver.registerContentObserver(Uri.parse("content://sms/"), true, new MyContentObserver(new Handler())); //注册内容监听
class MyContentObserver extends ContentObserver {
private static final String TAG = "MyContentObserver";
public MyContentObserver(Handler handler) {
super(handler);
}
/** * 当被监听的内容发生改变时回调 */
@Override
public void onChange(boolean selfChange) {
Log.i(TAG, "短信改变了");
Uri uri = Uri.parse("content://sms/outbox"); // 发件箱的uri // 查询发件箱的内容
Cursor cursor = getContentResolver().query(uri, new String[]{"address", "date", "body"}, null, null, null);
if(cursor != null && cursor.getCount() > 0) { String address; long date; String body;
while(cursor.moveToNext()) { address = cursor.getString(0); date = cursor.getLong(1); body = cursor.getString(2);
Log.i(TAG, "号码: " + address + ", 日期: " + date + ", 内容: " + body); }
cursor.close();
} } }
ContentProvider ContentResolver ContentObserver 内容:提供、访问、监听
标签:
原文地址:http://www.cnblogs.com/hanxing/p/4558229.html