1. Create a new case as follows:
2. Do not need to add permissions, while the layout files here do not modify, came to mainactivity, as follows:
1 PackageCom.itheima.sendsmslistener;2 3 ImportAndroid.net.Uri;4 ImportAndroid.os.Bundle;5 ImportAndroid.os.Handler;6 Importandroid.app.Activity;7 ImportAndroid.database.ContentObserver;8 ImportAndroid.view.Menu;9 Ten Public classMainactivityextendsActivity { One A @Override - protected voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); the Setcontentview (r.layout.activity_main); -Getcontentresolver (). Registercontentobserver (Uri.parse ("Content://sms"),true,NewMyobserver (NewHandler ())); - } - + - Private classMyobserverextendscontentobserver{ + A Publicmyobserver (Handler Handler) { at Super(handler); - } - - @Override - Public voidOnChange (BooleanSelfchange) { - Super. OnChange (selfchange); inSYSTEM.OUT.PRINTLN ("The SMS database has changed.") "); - //Query the database. to } + } -}
3. The program to the simulator, as follows:
To add a contact to the system contact, send a text message to this contact, as follows:
Observe the Logcat print log as follows:
09-15 07:42:33.109:i/system.out (644): The SMS database has changed.
09-15 07:42:34.739:i/system.out (644): The SMS database has changed.
09-15 07:42:35.189:i/system.out (644): The SMS database has changed.
We enter a text message sent, will print three logs, that is, the onchange () method was called 3 times, that is, the database changed 3 times, Why we input send a message, the database changed 3 times ?
A: This is because, we send text messages, SMS will go through 3 states: " draft "---> " send "---> " sent ";
(1) When we finish editing text messages, text messages form a draft, there is a tag field in the database, the tag field is marked as a number or a character (meaning that the text message is a draft ), this time the database changes, call a OnChange () method ;
(2) Form a draft text message to send, the database corresponding tag field changes (meaning SMS is being sent ), this time the database changes, call once again onchange () method ;
(3) After the text message is sent successfully, the text message is marked as sent , this time the database changes, the Last Call onchange () method ;
This has occurred 3 calls to the OnChange () method
Android (Java) Learning note 254:contentprovider used Content Viewer (observations sent by SMS)