When the data in the database changes, and we want to know the circumstances of the change, we need to monitor the change of the database. This task is done by the content watcher. Below this case, for the SMS database registered content observer, to monitor the change of text messages, when the text message database changes, to do the corresponding business processing can (here just print log)
The layout file is selected by default because no interface is available.
Take a look at the code in the main activity:
Package Com.itydl.contentobserver;import Android.net.uri;import Android.os.bundle;import android.os.Handler;import Android.app.activity;import Android.content.contentresolver;import Android.database.contentobserver;import Android.view.menu;public class Mainactivity extends Activity {@Override protected void onCreate (Bundle savedinstanc EState) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Registers a content observer, listens to the text message database content change Contentresolver CR = Getcontentresolver (); URI: listens to which URI the content provider's notification, the database URI//notifyfordescendents: If true, so long as the content://sms begins with the data change of the URI, you can receive notifications, such as content:/ /sms/inbox. Actually write dead true can//third parameter: Represents the instance of the content observer (inherited Contentobserver implementation class here) Cr.registercontentobserver (Uri.parse ("content://s MS "), True, new Myobserver (New Handler ())); } class Myobserver extends contentobserver{public myobserver (Handler Handler) {super (Handler);//Empty construction. No need to do any processing}//notification that a data change is received, this method calls @overridepublic voidOnChange (Boolean Selfchange) {//TODO auto-generated method Stubsuper.onchange (Selfchange); SYSTEM.OUT.PRINTLN ("SMS Database Change");} } }
Now you can run the program, then go to the simulator or phone, send a text message, change the SMS database. found that each message sent, or received a text message, log will be output.
Android Simple Combat Tutorial--the 21st session of "content observer monitoring database Changes"