前面有一篇关于Databases的NotifyChange:
http://aijiawang-126-com.iteye.com/blog/812004
其实这文章讲的就是通过ContentObserver来监测Databases的改变,并且做出相应的处理。
但对Databases的改变,除了可以通过ContentObserver来监测外,还可以通过DatasetObserver来监测。那我们来看看它们之间的区别
1,ContentObserver
Receives call backs for changes to content. Must be implemented by objects which are added to a ContentObservable.
接受回调去改变Content.
其实ContentObserver主要是通过Uri来监测特定的Databases的表:
比如:
public class TestContentObserver extends Activity {
MyContentObserver mco;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mco=new MyContentObserver(new MyHandler());
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
getApplicationContext().getContentResolver().registerContentObserver(Contacts.CONTENT_URI, true, mco);
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
class MyContentObserver extends ContentObserver{
public MyContentObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
@Override
public void onChange(boolean selfChange) {
// TODO Auto-generated method stub
super.onChange(selfChange);
System.out.println("onChange "+selfChange);
}
@Override
public boolean deliverSelfNotifications() {
// TODO Auto-generated method stub
return super.deliverSelfNotifications();
//return true;
}
};
}
registerContentObserver(Contacts.CONTENT_URI, true, mco);通过对Contacts.CONTENT_URI的监测,当Contacts发生变化就会call back回调mco里面的onChange方法来处理变化。
2,DatasetObserver
Receives call backs when a data set has been changed, or made invalid. The typically data sets that are observed are Cursors or Adapters. DataSetObserver must be implemented by objects which are added to a DataSetObservable.
DatasetObserver当数据集改变或者无效时,就会回调相应的函数做出处理,而典型的数据集就是cursor或者adapters.
这就是说通过cursor或者adapters的改变来做出相应的处理。
比如:QuickSearchBox中的SuggestionsAdapter
mSuggestionsAdapter.registerDataSetObserver(new SuggestionsObserver()); private class SuggestionsObserver extends DataSetObserver {
@Override
public void onChanged() {
updateInputMethodSuggestions();
}
}