简体   繁体   中英

How to get an incoming SMS' phone number?

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);
    }
}

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.(ie ). And in your Broadcast receiver class you have to mention <actionandroid:name="android.provider.Telephony.SMS_RECEIVED"> in your intent-filter.

使用getOriginatingAddress方法。

设置正确的清单文件设置以接收传入的SMS。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM