If the visitors of the ContentProvider need to know the changes in the data in the ContentProvider, you can call getContentResolver().notifyChange(uri,null) when the data changes in the ContentProvider to notify visitors registered on this URI.
public class PersonContentProvider extends ContentProvider[
public Uri insert(Uri uri,ContentValues values){
("person","personid",values);
getContext().getContentResolver().notifyChange(uri,null);
}//Notify visitors who are registered on this URI, and also register on the insert method}
If the visitors of ContentProvider need to receive data change notification, they must use ContentObserver to listen on the data (data is described using URI). When the data change notification is monitored, the system will call the ContentObserver's onChange() method.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_main);
Uri uri = ("content:///person");
this.getContentResolver().registerContentObserver(uri, true, new PersonContentdObserver(new Handler()));
// The third object is the listening object. When the data changes, the object is notified to make corresponding changes.
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(, menu);
return true;
}
private class PersonContentdObserver extends ContentObserver {
public PersonContentdObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
Uri uri = ("content:///person");
Cursor cursor = getContentResolver().query(uri, null, null, null,"personid desc limit 1");
while (()) {
String name = (("name"));
("Name", name);
}
(selfChange);
} }
}
Test application:
Button btn = (Button) findViewById();
(new OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = ("content:///person");// Get the content provider based on the identification name
ContentResolver cr = ();
ContentValues values = new ContentValues();
("name", "Livingstone");
("phone", "1101");
("amount", "1111111111");
(uri, values);
}
});