Send SMS Message in Android

Send SMS Message in Android

Android allows to send SMS messages directly from an application.

Application must have permission to send SMS messages. So, we need to request the SEND_SMS permission in the manifest file.

pp/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app">

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

    <application>
        ...
    </application>

</manifest>

Using the method ContextCompat.checkSelfPermission() we check if required permission was granted. If not, then we request permission by calling the method ActivityCompat.requestPermissions().

SmsManager manages SMS operations. We can use the getDefault() static method to get an instance of SmsManager. SMS message can be sent by using sendTextMessage() method.

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.telephony.SmsManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity()
{
    private val permission: String = Manifest.permission.SEND_SMS
    private val requestCode: Int = 1

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (ContextCompat.checkSelfPermission(this, permission)
            != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode)
        } else {
            sendSms()
        }
    }

    private fun sendSms()
    {
        val smsManager = SmsManager.getDefault()

        val phoneNumber = "154XXXXXXXX"
        val message = "Hello"
        smsManager.sendTextMessage(phoneNumber, null, message, null, null)
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.