Sending SMS in Android application with Kotlin

Add SEND_SMS permission in your manifest.

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

Import SmsManager

import android.telephony.SmsManager

Requesting permission

val PERMISSION_REQUEST = 101;
ActivityCompat.requestPermissions(
    this, arrayOf(Manifest.permission.SEND_SMS),
    PERMISSION_REQUEST
)

Checking if permission was allowed

val SMSpermissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
if (SMSpermissionCheck == PackageManager.PERMISSION_GRANTED) {
    //Woohoo! You got permission to send the SMS.
}

Finally sending the SMS

val myNumber = "123456789"
val myMsg = "Hello World!"
val smsManager = SmsManager.getSmsManagerForSubscriptionId(1) 
smsManager.sendTextMessage(myNumber, null, myMsg, null, null)

Here SmsManager.getSmsManagerForSubscriptionId(id) will get the SmsManager for your specific SIM card. If you want to send SMS from default SIM card you will use SmsManager.getDefaultSmsSubscriptionId()

Leave a Reply