Home » Android » Detect incoming call in android using kotlin not working-Exceptionshub

Detect incoming call in android using kotlin not working-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

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) 

}
}

How to&Answers: