0

How do I get an incoming SMS' phone number?

I wrote BroadcastReciever as in this link, but I don't get any output. Also the Toast message in that BroadcastReciever does not get displayed.

Here is another sms.java file for which I used that BroadcastReciever.

public class SMS extends Activity {
    /** Called when the activity is first created. */
    Button btn;
    EditText edt1;
    EditText edt2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn=(Button) findViewById(R.id.btn1);
        edt1=(EditText) findViewById(R.id.edt1);
        edt2=(EditText) findViewById(R.id.edt2);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String phone=edt1.getText().toString();
                String message=edt2.getText().toString();

                if (phone.length()>0 && message.length()>0)
                    sendSMS(phone, message);
                else
                    Toast.makeText(getApplicationContext(),
                        "Enter the phone_no & message.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void sendSMS(String phoneNumber, String message)
    {
        Intent i1 = new Intent(this, SMS.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0,
                                                     i1 , 0);
        SmsManager SMS1 = SmsManager.getDefault();
        SMS1.sendTextMessage(phoneNumber, null, message, pi, null);
    }
}
Community
  • 1
  • 1
Apple_Magic
  • 477
  • 8
  • 26

3 Answers3

2

You can get the phone number of incoming SMS in the following manner.

  Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
    String string = "";
    String phone = "";

    if (bundle != null)
    {
        //---receive the SMS message--
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];            
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); 
            phone = msgs[i].getOriginatingAddress();  // Here you can get the phone number of SMS sender.
            string += msgs[i].getMessageBody().toString(); // Here you can get the message body.
          }
     }

And important thing you need is to mention permission in menifest file.(i.e. ). And in your Broadcast receiver class you have to mention <actionandroid:name="android.provider.Telephony.SMS_RECEIVED"> in your intent-filter.

Akshay
  • 2,506
  • 4
  • 34
  • 55
1

Use the getOriginatingAddress method.

Emmanuel
  • 216
  • 2
  • 11
0

Set the correct manifest file settings for receiving an incoming SMS.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
omermuhammed
  • 7,365
  • 4
  • 27
  • 40