how to send sms in kotlin app

To send an SMS in a Kotlin app, you can use the SmsManager class provided by the Android framework. Here are the steps to send an SMS in Kotlin:

  1. Import the necessary classes: kotlin import android.telephony.SmsManager import android.content.Intent import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.IntentFilter

  2. Register a broadcast receiver to receive the delivery status of the SMS: kotlin val SENT_ACTION = "SMS_SENT" val DELIVERED_ACTION = "SMS_DELIVERED" val sentIntent = PendingIntent.getBroadcast(context, 0, Intent(SENT_ACTION), 0) val deliveredIntent = PendingIntent.getBroadcast(context, 0, Intent(DELIVERED_ACTION), 0) val sentReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // Handle sent SMS actions here } } val deliveredReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // Handle delivered SMS actions here } } context.registerReceiver(sentReceiver, IntentFilter(SENT_ACTION)) context.registerReceiver(deliveredReceiver, IntentFilter(DELIVERED_ACTION))

  3. Send the SMS: kotlin val smsManager = SmsManager.getDefault() smsManager.sendTextMessage(phoneNumber, null, message, sentIntent, deliveredIntent)

Here, phoneNumber is the recipient's phone number, and message is the content of the SMS.

  1. Handle the delivery status of the SMS: In the onReceive method of the broadcast receiver for the sent SMS, you can check the result code to determine if the SMS was sent successfully or not: kotlin when (resultCode) { RESULT_OK -> { // SMS sent successfully } SmsManager.RESULT_ERROR_GENERIC_FAILURE -> { // Generic failure } SmsManager.RESULT_ERROR_NO_SERVICE -> { // No service } SmsManager.RESULT_ERROR_NULL_PDU -> { // Null PDU } SmsManager.RESULT_ERROR_RADIO_OFF -> { // Radio off } }

Similarly, in the onReceive method of the broadcast receiver for the delivered SMS, you can check the result code to determine if the SMS was delivered successfully or not.

That's it! These steps should help you send an SMS in a Kotlin app. Remember to handle the necessary permissions in your AndroidManifest.xml file to send SMS messages.