Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to get the sender's phone number of an SMS message

I am trying to read a user's SMS messages and get the sender's phone number of those messages. When I try getting the sender's phone number of the message through the "address" column, it returns the phone number of the text's conversation (for example, if I send a message to a user with phone number X, the address column returns X instead of my phone number), not the phone number of the person that sent the message. Below is my Kotlin code:

var cursor = contentResolver.query(
    Uri.parse("content://sms/"),
    null,
    null,
    null,
    null
)

// Retrieve the IDs of the sender's name
var senderID = cursor!!.getColumnIndex("address")

// Iterate through every message
while (cursor!!.moveToNext()) {
    var messageSender = cursor.getString(senderID) // Get the sender of the message
    System.out.println("---------------------------------------------------------")
    System.out.println(messageSender) // Returns phone number of the conversation, not the sender
}

For example: user with phone number 123456789 sends a message to you. I want to retrieve phone number 123456789.

like image 620
Adam Lee Avatar asked Nov 06 '22 12:11

Adam Lee


1 Answers

I found a solution. You must use the type column to identify whether the message has been sent or received.
When the message has been sent, you can read the phone number from the Telephony Manager.

fun getMessageSender(cursor: Cursor): String {
        val partnerAddressId = cursor.getColumnIndex("address")
        val typeId = cursor.getColumnIndex("type")

        val partnerAddress = cursor.getString(partnerAddressId)
        val type = cursor.getString(typeId)

        return if (type.equals("1", true)) {
            partnerAddress
        } else {
            getPhoneNumber()
        }
    }
private fun getPhoneNumber(): String {
        val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return telephonyManager.line1Number
    }

But please note that I do not know how this affects devices with Multi Sim. I could imagine that the wrong number will be returned here.

I have worked out this solution in combination with the following posts:
Getting phone number of each sms via content://sms/
Programmatically obtain the phone number of the Android phone

like image 114
RobDev Avatar answered Nov 15 '22 06:11

RobDev