Android sends SMS automatically when a button is pressed

I try to automatically send an SMS to a specific 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 brings me to another screen where I can edit my text and click "Submit". I just want him to do this process automatically without transferring me to another screen. Since I already defined my message, I just want to send it to a specific number.

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

thanks

+6
source share
4 answers

Try this code:

  String messageToSend = "this is a message"; String number = "2121234567"; SmsManager.getDefault().sendTextMessage(number, null, messageToSend, null,null); 

As for the number, you need to enter the number as if you called him from the phone or sent an SMS message in the usual way.

+17
source

You can also use assembly in Intent:

  buttonSendSms_intent.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub String smsNumber = edittextSmsNumber.getText().toString(); String smsText = edittextSmsText.getText().toString(); Uri uri = Uri.parse("smsto:" + smsNumber); Intent intent = new Intent(Intent.ACTION_SENDTO, uri); intent.putExtra("sms_body", smsText); startActivity(intent); }}); 
+3
source

try it

 private static final String SMS_SENT_INTENT_FILTER = "com.yourapp.sms_send"; private static final String SMS_DELIVERED_INTENT_FILTER = "com.yourapp.sms_delivered"; String message = "hey, this is my message"; String phnNo = " " //preferable use complete international number PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent( SMS_SENT_INTENT_FILTER), 0); PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent( SMS_DELIVERED_INTENT_FILTER), 0); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phnNo, null, message, sentPI, deliveredPI); 
+2
source

an easy way is to use SmsManager.Telephony.

+2
source

Source: https://habr.com/ru/post/915840/


All Articles