如何获取收到短信的电话号码?

时间:2011-04-17 13:54:50

标签: android

如何获取传入短信的电话号码?

我在this link中写了BroadcastReciever,但我没有得到任何输出。此BroadcastReciever中的Toast消息也不会显示。

这是另一个sms.java文件,我使用了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);
    }
}

3 个答案:

答案 0 :(得分:2)

您可以通过以下方式获取传入短信的电话号码。

  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.
          }
     }

你需要的重要一点是提及清单文件的许可。(即)。在您的广播接收器类中,您必须在intent-filter中提及<actionandroid:name="android.provider.Telephony.SMS_RECEIVED">

答案 1 :(得分:1)

使用getOriginatingAddress方法。

答案 2 :(得分:0)

设置接收来电短信的correct manifest file settings