Recently, a friend asked me how to receive text messages from a specified number, and asked me not to allow the system to intercept messages to users. It's a good time to look at tianchao group. A friend also asked this question and solved it through the contentobserver method. I will paste the code I implemented here for your reference.
You can listen to the contentprovider of the corresponding Uri, and implement what you want to do or broadcast in onchange.
[Java]
View plaincopy
- Public class screentest extends activity {
- Class smscontent extends contentobserver {
- Private cursor = NULL;
- Public smscontent (handler ){
- Super (handler );
- }
- /**
- * @ Description this method is called when the text message table is changed
- * Two permissions are required.
- * Android. Permission. read_sms reads text messages
- * SMS writing for Android. Permission. write_sms
- * @ Author snake
- * @ Date 2010-1-12
- */
- @ Override
- Public void onchange (Boolean selfchange ){
- // Todo auto-generated method stub
- Super. onchange (selfchange );
- // Read the text message of the specified number in the inbox
- Cursor = managedquery (URI. parse ("content: // SMS/inbox"), new string [] {"_ id", "Address", "read"}, "address =? And read =? ", New string [] {" 12345678901 "," 0 "}," date DESC ");
- If (cursor! = NULL ){
- Contentvalues values = new contentvalues ();
- Values. Put ("read", "1"); // modify the text message to read mode.
- Cursor. movetofirst ();
- While (cursor. islast ()){
- // Update the status of the currently unread SMS to read
- Getcontentresolver (). Update (URI. parse ("content: // SMS/inbox"), values, "_ id =? ", New string [] {" "+ cursor. getint (0 )});
- Cursor. movetonext ();
- }
- }
- }
- }
- /** Called when the activity is first created .*/
- @ Override
- Public void oncreate (bundle savedinstancestate ){
- Super. oncreate (savedinstancestate );
- Setcontentview (R. layout. Main );
- Smscontent content = new smscontent (new handler ());
- // Register the SMS change listener
- This. getcontentresolver (). registercontentobserver (URI. parse ("content: // SMS/"), true, content );
- }
- }