Android send SMS automatically on button click

Alex picture Alex · May 15, 2012 · Viewed 45.8k times · Source

I am trying to automatically send SMS message to a certain number when the user presses a button on the screen.

This is my code:

Intent smsIntent = new Intent(Intent.ACTION_SENDTO,
Uri.parse("sms:xxxxxxxxxxx")); 
smsIntent.putExtra("sms_body", "Hello");
startActivity(smsIntent);

xxxxxxx = phone number

I have the following permissions:

<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

When I press the button it takes me to another screen where I can edit my text and press Send. I just want it to do this process automatically without taking me to another screen. As I've already defined my message, I just want to send it to a particular number.

And also I am not sure if I put the corrent phone number in the second line of code. Do I have to put my country code in there first or can I just put my mobile phone number and it will work?

Thank you

Answer

Chris Thompson picture Chris Thompson · May 15, 2012

Try this code:

 String messageToSend = "this is a message";
 String number = "2121234567";

 SmsManager.getDefault().sendTextMessage(number, null, messageToSend, null,null);

With regards to the number, you need to enter the number as if you were calling it from the phone or sending an sms message in the normal manner.