I am writing an application that communicates with other devices through SMSs.
I was able to implement a listener for received SMSs. The thing is that it is listening to all received messages. I would like to only listen received SMSs from a specific number.
Here is my onReceive
method.
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
// show first message
Toast toast = Toast.makeText(context,
"Received SMS: " + smsMessage[0].getMessageBody(),
Toast.LENGTH_LONG);
toast.show();
}
There is no way AFAIK to filter for a number just by the intent.
What you CAN do is to get phone number in the Receiver like this:
SMSMesssage msg=SMSMessage.creatFromPdu(pdu)
String origination_no = msg.getDisplayOriginatingAddress()
Use PhoneNumberUtils.compare() to compare phone numbers as there are different phone number formats (+4XXXX, 0XXXX...). You can get the sender via getOriginatingAddress().
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
// get sms objects
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus.length == 0) {
return;
}
// large message might be broken into many
SmsMessage[] messages = new SmsMessage[pdus.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
sb.append(messages[i].getMessageBody());
}
String sender = messages[0].getOriginatingAddress();
String message = sb.toString();
// apply sms filter
if (PhoneNumberUtils.compare("your number", sender)) {
// do something
}
}
}
}
Use this
for(int i=0; i<smsMessage.length; i++) {
smsMessage[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
String msg_from = msgs[i].getOriginatingAddress();
Log.v("msg_from >>",msg_from);
if(msg_from.equals("1234556"))
{
//do you stuff here.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With