5

I am trying to build an app whereby the user clicks a submit button which will send the contents of their input via SMS to a predefined number. Being very new to Kotlin, I have been helped with the code to send the data via SMS, however it opens up the default messaging app and the user has to interact with the messaging app and then navigate back to my app. What I would like is for this to happen in the background and send directly from my app. The code is below...Any help greatly appreciated, Many thanks

class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)


val backbut = findViewById<Button>(R.id.backbut)
backbut.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)

}

var spinner: Spinner? = null
spinner = this.spinner


val sub1: Button = findViewById<Button>(R.id.sub1)
sub1.setOnClickListener {
val cust: String = cust.text.toString()
val reg: String = reg.text.toString()
val pal: String = pal.text.toString()
val cont:String = cont.text.toString()
val data: String =
"CUSTOMER : ".plus(cust).plus("\n").plus("CONTAINER : ").plus(cont).plus("\n").plus("VEH 
REG : ").plus(reg).plus("\n").plus("PALLETS : ")
.plus(pal)
startActivity(getSendSmsIntent("1234567", data))

}
}
// textview_selected!!.text = "Selected : "+ Spinner [position]


private fun getSendSmsIntent(phoneNumber: String, content: String?): Intent? {

val uri = Uri.parse("smsto:$phoneNumber")
val intent = Intent(Intent.ACTION_SENDTO, uri)

intent.putExtra("sms_body", content)

return getIntent(intent, true)
}
private fun getIntent(intent: Intent, isNewTask: Boolean): Intent? {
return if (isNewTask) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) else intent

}

}

1 Answer 1

8

After reading the documentation, I think you can achieve your needs using the following code :

private fun sendSMS(phoneNumber: String, message: String) {
        val sentPI: PendingIntent = PendingIntent.getBroadcast(this, 0, Intent("SMS_SENT"), 0)
        SmsManager.getDefault().sendTextMessage(phoneNumber, null, message, sentPI, null)
    }

Add this permission to your AndroidManifest and make sure it's granted :

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

Call sendSMS method as follows :

 sendSMS("+2126000000", "Some text here")

Screenshot :

1
  • @GlennArnold feel free to mark this as answered (tick mark on the left of the answer) Oct 3, 2020 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.