When the device receives a new SMS message, it broadcasts an intent containing the Android. provider. telephony. sms_received action. Note that this action is a string value, and SDK 1.0 no longer contains references to this string. Therefore, you need to explicitly specify it in your application.
For an application to listen to SMS intent broadcast, you must first add the receive_sms permission. Add a uses-permission to the application manifest, as shown in the following snippet:
<Uses-Permission Android: Name = "android. Permission. receive_sms"/>
The SMS broadcast intent contains details about the new SMS. To extract the smsmessage object array packaged in the bundle of the SMS broadcast intent, use the PDUS key to extract the sms pdus array. Each object represents an SMS message. Convert each PDU byte array into a smsmessage object and call smsmessage. createfrompdu to input each byte array, as shown in the following snippet:
Bundle bundle = intent. getextras ();
If (bundle! = NULL ){
Object [] PDUS = (object []) bundle. Get ("PDUS ");
Smsmessage [] messages = new smsmessage [PDUS. Length];
For (INT I = 0; I <PDUS. length; I ++)
Messages [I] = smsmessage. createfrompdu (byte []) PDUS [I]);
}
Each smsmessage object contains the details of the SMS message, including the source address (mobile phone number), time, and message body.
The following example demonstrates how a broadcast receiver implements the onreceive function to check whether the new SMS starts with the @ echo string. If yes, send the same text to the mobile phone:
Public class incomingsmsreceiver extends broadcastreceiver
{
Private Static final string querystring = "@ echo";
Private Static final string sms_received = "android. provider. telephony. sms_received ";
Public void onreceive (context _ context, intent _ intent)
{
If (_ intent. getaction (). Equals (sms_received ))
{
Smsmanager SMS = smsmanager. getdefault ();
Bundle bundle = _ intent. getextras ();
If (bundle! = NULL)
{
Object [] PDUS = (object []) bundle. Get ("PDUS ");
Smsmessage [] messages = new smsmessage [PDUS. Length];
For (INT I = 0; I <PDUS. length; I ++)
Messages [I] = smsmessage. createfrompdu (byte []) PDUS [I]);
For (smsmessage message: messages)
{
String MSG = message. getmessagebody ();
String to = message. getoriginatingaddress ();
If (msg. tolowercase (). startswith (querystring ))
{
String out = msg. substring (querystring. Length ());
SMS. sendtextmessage (to, null, out, null, null );
}
}
}
}
}
}
To listen to text messages, use the intent filter to register the broadcast receiver and enable it to listen to the Android. provider. telephony. sms_received action, as shown in the following snippet:
Final string sms_received = "android. provider. telephony. sms_received ";
Intentfilter filter = new intentfilter (sms_received );
Broadcastreceiver receiver ER = new incomingsmsreceiver ();
Registerreceiver (receiver, filter );