To send a text message from our application to the native android message app directly. Yes, We can do that by write some lines of code and providing permission.
First, we need to add required permission in AndroidManifest.xml as below.
// Only send permission is ok if we just want to send message only
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
Second, we just have to write a few lines of code for sending SMS as below.
fun sendSms(phoneNo: String, message: String) { val SENT = "SMS_SENT" val DELIVERED = "SMS_DELIVERED" val sentPI = PendingIntent.getBroadcast(this@Activity, 0, Intent(SENT), 0) val deliveredPI = PendingIntent.getBroadcast(this@Activity, 0, Intent(DELIVERED), 0) registerReceiver(object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (resultCode) { Activity.RESULT_OK -> { Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show(); } SmsManager.RESULT_ERROR_GENERIC_FAILURE -> { Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show(); } SmsManager.RESULT_ERROR_NO_SERVICE -> { Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show(); } SmsManager.RESULT_ERROR_NULL_PDU -> { Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show(); } SmsManager.RESULT_ERROR_RADIO_OFF -> { Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show(); } } } }, IntentFilter(SENT)) registerReceiver(object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (resultCode) { Activity.RESULT_OK -> { Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_SHORT).show(); } Activity.RESULT_CANCELED -> { Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show(); } } } }, IntentFilter(DELIVERED)) try { val smsManager = SmsManager.getDefault() smsManager.sendTextMessage( phoneNo, null, message, sentPI, deliveredPI) Toast.makeText(applicationContext, "Message Sent", Toast.LENGTH_LONG).show() } catch (ex: Exception) { Toast.makeText(applicationContext, ex.message.toString(), Toast.LENGTH_LONG).show() ex.printStackTrace() } }
Finally, we just need to call sendSms() method to send message as below and message will be send.
sendSms("84xxxxx007", "Hello Pinkal, How are you?")
To send the same message to multiple phones number we just have call sendSms() multiple times as below example.
val phoneNoList = arrayOf("84xxxxx007", "84xxxxx008", "84xxxxx009", "84xxxxx010") for (phoneNo in phoneNoList) { sendSms(phoneNo, "Hello Pinkal, How are you?") }