Search code examples
androidbroadcastreceiversms

How to get an incoming sms with broadcast receiver?


I have the following code:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val br = MyBroadcastReceiver()
        val filter = IntentFilter(Intent.ACTION_PROCESS_TEXT)
        val receiverFlags = ContextCompat.RECEIVER_EXPORTED

        ContextCompat.registerReceiver(
            applicationContext,
            br,
            filter,
            receiverFlags
        )

        setContent {
            Text("The app is now running")
        }
    }
}

class MyBroadcastReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent?) {
        Log.d("qwer", "${intent?.action}")
    }
}

I expect to see a message in logcat after sending sms, but i don't see any. I assume that the wrong specified action in the intent filter is the reason, but i don't know what is the correct action for getting sms's. Can you help with it ?


Solution

  • You are using the wrong Intent action. You need to use this one:

    android.provider.Telephony.Sms.Intents.SMS_RECEIVED_ACTION

    You also need to have the necessary permissions declared in the manifest:

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