First, a brief introduction: Managedquery ()
Parameters:
1.uri:content Provider The resource index that needs to be returned. For example: Receive the mailbox:
The code is as follows |
Copy Code |
Content://sms/inbox |
2.Projection: Identifies which columns need to be included in the return data. For example: ID number, address, message body, read status ...
The code is as follows |
Copy Code |
New string[] {"_id", "address", "body", "read"} |
3.Selection: Filter parameters that match the criteria for a query.
The code is as follows |
Copy Code |
"Address=?" and read=? " |
4.SelectionArgs: Ditto
The code is as follows |
Copy Code |
New string[] {"15061978220", "1"} |
5.SortOrder: Arrange the return information.
The code is as follows |
Copy Code |
"Date desc" |
Two questions to face: 1. How to extract the body of the message.
2. How to extract the effective information in the body.
The code is as follows |
Copy Code |
String smsbody = cursor.getstring (Cursor.getcolumnindex ("body")); String code = smsbody.substring (Smsbody.indexof (",") +1, Smsbody.indexof (".")); |
Extract the substring with substring to "," "Start,". End Gets the position of the string with indexof ("").
Now attach the source program
The code is as follows |
Copy Code |
Package My.learn.ReadSMS; Import android.app.Activity; Import Android.database.Cursor; Import Android.net.Uri; Import Android.os.Bundle; Import Android.view.View; Import Android.widget.Button; Import Android.widget.TextView; public class Readsmsactivity extends activity { Final String sms_url_inbox= "Content://sms/inbox"; Private Button mybtn; Private TextView Mttxt; /** called when the "activity is" is a created. */ @Override & nbsp public void OnCreate (Bundle savedinstancestate) { super.oncreate ( Savedinstancestate); Setcontentview (R.layout.main); mybtn = (Button) Findviewbyid (R.id.clickbutton); mttxt = (TextView) Findviewbyid (r.id.showtxt); } public void doreadsms (view view) { Cursor Cursor = null;//cursor cursor = managedquery (Uri.parse ("Content://sms/inbox"), New string[] { _id "," Address "," body "," read "}," address=? " And read=? ", New String[] {"15061978220", "1"}, "date desc"); if (cursor!= null) {//If SMS is read-mode & nbsp; Cursor.movetofirst (); if (Cursor.movetofirst ()) { String smsbody = cursor . GetString (Cursor.getcolumnindex ("body")); String code = smsbody.substring (Smsbody.indexof (",") + 1, Smsbody.indexof (".")); Mttxt.settext (Code.tostring ()); } } } } |
In the absence of a real machine, we can use the simulator to achieve.
First in the DDMS mode, "Emulator control", "Incoming number", select "SMS", fill in the required "message", click the "Send" button, so that the simulator can receive text messages.
Program Run Result: