If the visitor of ContentProvider needs to know the data changes in ContentProvider, you can call getContentResolver (). policychange (uri, null) When ContentProvider changes data to notify the visitor registered on this URI.
Copy codeThe Code is as follows: public class PersonContentProvider extends ContentProvider [
Public Uri insert (Uri uri, ContentValues values ){
Db. insert ("person", "personid", values );
GetContext (). getContentResolver ().
NotifyChange(Uri, null );
} // Notify the visitor registered on this URI and registered on the insert method}
If the visitor of ContentProvider needs to be notified of data changes, you must use ContentObserver to listen to the data (the data uses the URI description). When the notification of data changes is received, the system will call the onChange () method of ContentObserver.Copy codeThe Code is as follows: public class MainActivity extends Activity {
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
Uri uri = Uri. parse ("content: // cn. wordtech. providers. personprovider/person ");
This. getContentResolver (). registerContentObserver (uri, true, new PersonContentdObserver (new Handler ()));
// The third object is the listener object. When the data changes, the object is notified to change accordingly.
}
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
GetMenuInflater (). inflate (R. menu. main, menu );
Return true;
}
Private class PersonContentdObserver extends ContentObserver {
Public PersonContentdObserver (Handler handler ){
Super (handler );
}
@ Override
Public void onChange (boolean selfChange ){
Uri uri = Uri. parse ("content: // cn. wordtech. providers. personprovider/person ");
Cursor cursor = getContentResolver (). query (uri, null, "personid desc limit 1 ");
While (cursor. moveToNext ()){
String name = cursor. getString (cursor. getColumnIndex ("name "));
Log. I ("Name", name );
}
Super. onChange (selfChange );
}}
}
Test application:
Copy codeThe Code is as follows: Button btn = (Button) findViewById (R. id. btn );
Btn. setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View v ){
Uri uri = Uri. parse ("content: // cn. wordtech. providers. personprovider/person"); // obtain the content provider based on the Identification name
ContentResolver cr = MainActivity. this. getContentResolver ();
ContentValues values = new ContentValues ();
Values. put ("name", "Livingstone ");
Value. put ("phone", "1101 ");
Values. put ("amount", "1111111111 ");
Cr. insert (uri, values );
}
});