0

could not find any reference on using kotlin to detect incoming call using BroadcastReceiver created dynamically. most java program add intent in the manifest. I wanted to use Broadcastreciever in the specific activity. I used below code but not working. Can anyone help?

Problem:
1. How to set up the Intent Filter for the Phone_State

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)


    val broadCastReceiver = object : BroadcastReceiver() {

        override fun onReceive(contxt: Context?, intent: Intent?) {

            try {
                println("Receiver start")

                val state = intent!!.getStringExtra(TelephonyManager.EXTRA_STATE)
                val incomingNumber =
                    intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)
                if (state == TelephonyManager.EXTRA_STATE_RINGING) {
                    Toast.makeText(applicationContext, "Incoming Call State", Toast.LENGTH_SHORT).show()
                    Toast.makeText(applicationContext,
                        "Ringing State Number is -$incomingNumber",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                if (state == TelephonyManager.EXTRA_STATE_OFFHOOK) {
                    Toast.makeText(applicationContext, "Call Received State", Toast.LENGTH_SHORT).show()
                }
                if (state == TelephonyManager.EXTRA_STATE_IDLE) {
                    Toast.makeText(applicationContext, "Call Idle State", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    // Set When broadcast event will fire.
    val filter = IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED)
    LocalBroadcastManager.getInstance(this).registerReceiver(broadCastReceiver, filter) 

} }

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
MilkBottle
  • 4,242
  • 13
  • 64
  • 146
  • did you tried https://stackoverflow.com/questions/15563921/how-to-detect-incoming-calls-in-an-android-device – Animesh Sahu Feb 21 '20 at 14:00
  • @animesh, I am confused about how to use the CallReceiver declared in manifest. How to use it inside activity say MainActivity? – MilkBottle Feb 22 '20 at 02:20

0 Answers0