需求 :
有两个应用,com.itheima.contentProvider和com.itheima.contentObserver,
在 contentObserver 应用中,监控 contentProvider 中的一个数据库info.db中的person表,
每当这个perosn表被插入了一条数据,就往contentObserver应用中发回一个通知,来说明person表被插入了.
这实际上就是从一个应用 A 发送一条通知到应用 B ,在其中起到桥接的 就是这两个应用都注册了相同的Uri.
思路 :
每当往 person 表中插入数据时,都需要调用 ContentProvider 类中的 insert 函数,所以,可以将发送通知的那一行
代码放在insert函数中.剩下的就是在 com.itheima.contentObserver 中注册个内容观察者和一个相同的Uri,然后等着接收通知.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -com.itheima.contentObserver应用- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
步骤 :
1,在该应用的 MainActivity 中得到个内容解决者对象resolver.
2, 定义个内容观察者的类,要重写其中的 onChange 函数,该函数的作用就是,每当有通知发来时,该函数就会被自动调用.
3, 并在该内容解决者resolver中注册个 Uri 和内容观察者.
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
<span style="white-space:pre"> </span>// 1, 得到个内容解决者对象
ContentResolver resolver = getContentResolver();
//3,并且在在该对象上注册个内容观察者,传入uri.
Uri uri = Uri.parse("content://com.itheima");
resolver.registerContentObserver(uri,true, new MyObserver(new Handler()));
}
<span style="font-family: Arial, Helvetica, sans-serif;">//2, 定义个内容观察者的类,要重写其中的 onChange 函数,该函数的作用就是,每当收到发来的通知时,该函数就会被自动调用.</span>
class MyObserver extends ContentObserver{
public MyObserver(Handler handler) {
super(handler);
}
public void onChange(boolean selfChange) {
System.out.println("通知 : person表被插入了一条数据!");
}
}
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -com.itheima.contentProvider应用- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
步骤 :
1,在应用中的内容提供者类中,有个 insert 方法,每当往表中插入一条数据时,都要调用该insert 方法,
2,所以,将发送通知的那行代码 放在insert 函数中.
public Uri insert(Uri uri, ContentValues values) {
if(uriMatcher.match(uri) == 1000)
{
//开始往数据库的表中插入一条数据
SQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext(), "info.db");
SQLiteDatabase db = openHelper.getWritableDatabase();
db.insert("person", null, values);
System.out.println("插入数据成功!");
//就在这里发出通知,说明person表改变了,该通知是发送给 com.itheima.ContentObserver 应用的
Uri uri_1 = Uri.parse("content://com.itheima");
getContext().getContentResolver().notifyChange(uri_1, null);//这里的uri_1要和上面com.itheima.contentObserver应用中注册的uri要一致
db.close();
}else{
throw new RuntimeException("Uri不匹配");
}
return null;
}