Content Observer:
When the database data of the application is changed, the content provider notifies the content provider to register a content observer on the URI, and can receive notification of changes to the data.
Implementation steps:
1. If it is a custom contentprovider, the following code needs to be implemented in the method of data transmission change:
1 contentresolver cr = getcontext (). Getcontentresolver (); 2 // notification that all content observers registered on this URI can be notified 3 null);
Notifychange (URI URI, contentobserver observer)//parameter Uri: uri//parameter for content send change Observer: can be NULL if specified as a content observer, a bit similar to the final receiver of the broadcast ; If you register the content observer, true 2. Register a content watcher where you want to accept the data change notification
1 Importandroid.app.Activity;2 ImportAndroid.content.ContentResolver;3 ImportAndroid.database.ContentObserver;4 ImportAndroid.net.Uri;5 ImportAndroid.os.Bundle;6 ImportAndroid.os.Handler;7 8 Public classMainactivityextendsActivity {9 Ten @Override One protected voidonCreate (Bundle savedinstancestate) { A Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); - Initlinstener (); the } - - Private voidInitlinstener () { -Contentresolver cr=getcontentresolver (); +Cr.registercontentobserver (Uri.parse ("Content://sms"),true,NewMyobserver (NewHandler ())); - } + A classMyobserverextendscontentobserver{ at - Publicmyobserver (Handler Handler) { - Super(handler); - } - //This method is called when the content watcher receives a notification that the database has changed - @Override in Public voidOnChange (BooleanSelfchange) { - Super. OnChange (selfchange); toSYSTEM.OUT.PRINTLN ("SMS Database send changes! "); + } - } the *}
Registercontentobserver (Uri Uri, Boolean notifyfordescendents, Contentobserver observer)
Parameter URI: listens to which URI the content provider's notice//parameter notifyfordescendents:false, need to match exactly, when true, need to be the URI that starts with the URI data changes, can receive the notification// Parameter Observer: The object of the callback when sending the change needs to implement a myobserver to implement Contentobserver. and implement the OnChange () method in the class.
Content Viewer for Android development