How to Connect native android / Kotlin functionality to react native?

Viewed 279

I have implemented SMSBroadcast Receiver functionality in native android (Kotlin) code.

The functionality is like whenever a new text message (SMS) is received I need to call an api (even the app is in background).

When i run as standalone android application its working fine. But how to integrate this with my react-native app?

The below is the code i wrote natively.


import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import android.util.Log
import android.widget.Toast
import com.reactnativecommunity.asyncstorage.AsyncLocalStorageUtil
import com.reactnativecommunity.asyncstorage.ReactDatabaseSupplier

class SMSBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        Log.i(
            TAG,
            "Intent received: " + intent.action
        )
        if (intent.action === SMS_RECEIVED) {
            val bundle = intent.extras
            var data = ""
            if (bundle != null) {
                val pdus =
                    bundle["pdus"] as Array<Any>?
                val messages =
                    arrayOfNulls<SmsMessage>(pdus!!.size)
                for (i in pdus.indices) {
                    messages[i] =
                        SmsMessage.createFromPdu(pdus[i] as ByteArray)
                }
                if (messages.size > -1) {
                    data = messages[0]!!.messageBody
                    Log.i(
                        TAG,
                        "Message recieved: $data"
                    )
                }
            }
            Toast.makeText(context,"Message received : $data", Toast.LENGTH_LONG).show()
//            var accessToken = AsyncLocalStorageUtil.getItemImpl(ReactDatabaseSupplier.getInstance(context).get(), "");
//            if (accessToken != null){
//                
//            }
            if(listener!= null)
            {
                listener?.onSmsReceive(data)
            }
        }
    }

    companion object {
        private const val SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"
        private const val TAG = "SMSBroadcastReceiver"
        var listener : OnCustomSmsListener ?= null
    }
}

** Package suggestions are also welcome **

0 Answers
Related