Android listens to SMS messages
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:
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 );