Check if incoming SMS is from favorite contact


#1
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import java.util.*

const val SMS_BUNDLE = "pdus"

class SMSReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {

        val intentExtras = intent.extras
     //   val slot = intentExtras.getInt("slot", -1)
        val subId = intentExtras.getInt("subscription", -1)
        val sms = intentExtras.get(SMS_BUNDLE) as Array<Any>

        (0 until sms.size).forEach { i ->
            val format = intentExtras.getString("format")
            val smsMessage = SmsMessage.createFromPdu(
                    sms[i] as ByteArray,
                    format
            )

            var smsBody = smsMessage.messageBody.toString()
            val matchResult = regEx.find(smsBody)
            var address = smsMessage.originatingAddress

           // Check if Address is in getFavoriteContacts(context) 
           // Note: The contact may not be saved with international code
        }
    }
}

Below is the code to get the favorite contacts:

import android.content.Context
import android.provider.ContactsContract
import android.content.Intent
import android.net.Uri


fun getFavoriteContacts(context: Context): Map<*, *> {

    lateinit var contactMap : HashMap<String, String>

    val queryUri = ContactsContract.Contacts.CONTENT_URI.buildUpon()
            .appendQueryParameter(ContactsContract.Contacts.EXTRA_ADDRESS_BOOK_INDEX, "true")
            .build()

    val projection = arrayOf(
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.STARRED
    )

    val selection = ContactsContract.Contacts.STARRED + "='1'"

    val cursor = context.getContentResolver().query(queryUri,
            projection, selection, null, null)

    while (cursor.moveToNext()) {
        val contactID = cursor.getString(cursor
                .getColumnIndex(ContactsContract.Contacts._ID))

        val intent = Intent(Intent.ACTION_VIEW)
        val uri = Uri.withAppendedPath(
                ContactsContract.Contacts.CONTENT_URI, contactID.toString())
        intent.data = uri
        val intentUriString = intent.toUri(0)

        val title = cursor.getString(
                cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))

        contactMap[title] = intentUriString
    }

    cursor.close()
    return contactMap
}