androidkotlinandroid-studiosmssmsmanager

Problem in sending and receiving sms (Kotlin Android)


LoginActivity.kt:

if (checkSelfPermission(android.Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED
        || checkSelfPermission(android.Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED
        || checkSelfPermission(android.Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED
    ) {
        requestPermissions(
            arrayOf(android.Manifest.permission.RECEIVE_SMS,
                android.Manifest.permission.SEND_SMS,
                android.Manifest.permission.READ_SMS), PackageManager.PERMISSION_GRANTED
        )
    }

signInBtn.setOnClickListener {

fun sendSms(phoneNumber: String, message: String) {
    val smsManager = SmsManager.getDefault()
    smsManager.sendTextMessage(phoneNumber, null, message, null, null)
   }
}

sendSms("50004000151398","OK")

the main problem is this warning : getDefault() : SmsManager! is deprecated

I have tested some answers I’ve read :

val smsManager = getSystemService(SmsManager::class.java)

OR

val smsManager = applicationContext.getSystemService(SmsManager::class.java)

None of them workes ; after running app with all these solutions, the app crashes (app stops)

ERROR:

java.lang.SecurityException: Sending SMS message: uid 10185 does not have android.permission.SEND_SMS.

I’ve added permissions in Manifest.xml:

<uses-feature
    android:name="android.hardware.telephony"
    android:required="true" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>

What is the solution?


Solution

  • According to documentation it is not enough just to add android.permission.SEND_SMS to manifest, because its protection level is dangerous.

    You have to ask for this permission at runtime.