内容观察者ContentObserver原理
内容观察者ContentObserver原理
1、注册了内容观察者的应用 getContext().getContentResolver().notifyChange(Uri.parse("content://aaa.bbb.cccc"), null); 当数据变化时,大吼一声,给相应的ContentObserver 参数一:就是数据变化时,给的uri,观察者使用该uri,观察该应用的数据变化 参数二:如果为null,那么是所有的,如果为指定的ContentObserver,那只有该观察者可以接收到。 2、内容观察者: Uri uri = Uri.parse("content://aaa.bbb.cccc");
getContentResolver().registerContentObserver(uri, true, new MyObserver(new Handler())); |
应用A——内容提供者 @Override
public Uri insert(Uri uri, ContentValues values) {
int result = mather.match(uri);
if(result==OK){//口令正确
SQLiteDatabase db = helper.getWritableDatabase();
db.insert("person", null, values);
db.close();
System.out.println("添加了....");
getContext().getContentResolver().notifyChange(Uri.parse("content://aaa.bbb.cccc"), null);
}else{
throw new IllegalArgumentException("口令失败,滚犊子..");
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int result = mather.match(uri);
if(result==OK){//口令正确
SQLiteDatabase db = helper.getWritableDatabase();
db.delete("person", selection, selectionArgs);
db.close();
getContext().getContentResolver().notifyChange(Uri.parse("content://aaa.bbb.cccc"), null);
}else{
throw new IllegalArgumentException("口令失败,滚犊子..");
}
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int result = mather.match(uri);
if(result==OK){//口令正确
SQLiteDatabase db = helper.getWritableDatabase();
db.update("person", values, selection, selectionArgs);
db.close();
getContext().getContentResolver().notifyChange(Uri.parse("content://aaa.bbb.cccc"), null);
}else{
throw new IllegalArgumentException("口令失败,滚犊子..");
}
return 0;
}
另外一个应用——通过内容提供者操作应用A的数据
/**
* 2、插入数据insert
*
* @param view
*/
public void insert(View view) {
ContentResolver resolver = this.getContentResolver();
ContentValues values = new ContentValues();
values.put("name", "小胜");
values.put("phone", "110");
// Uri url = Uri.parse("content://cn.zengfansheng.db.personprovider/person/insert");
Uri uri = Uri.parse("content://com.itheima.db/person");
resolver.insert(uri, values);
Log.i(TAG, "插入数据成功");
}
/**
* 3、更新数据update
*
* @param view
*/
public void update(View view) {
ContentResolver resolver = this.getContentResolver();
// Uri uri =
// Uri.parse("content://cn.zengfansheng.db.personprovider/person/update");
Uri uri = Uri.parse("content://com.itheima.db/person");
ContentValues values = new ContentValues();
values.put("phone", "1111111111");
int update = resolver.update(uri, values, "name=?",new String[] { "小胜" });
if (update > 0) {
Log.i(TAG, "更新数据成功");
}
}
/**
* 4、删除数据delete
*
* @param view
*/
public void delete(View view) {
ContentResolver resolver = this.getContentResolver();
// Uri uri = Uri.parse("content://cn.zengfansheng.db.personprovider/person/delete");
Uri uri = Uri.parse("content://com.itheima.db/person");
int delete = resolver.delete(uri, "name=?", new String[] { "小胜" });
if (delete > 0) {
Log.i(TAG, "删除数据成功");
}
}
内容观察者监听应用A的大吼——内容观察者原理
|
结果:
|