This PhoneStateListener only works if the app is open for API>28(P) but i want the incoming/outgoing phone number even if the app is closed just like it works in API<=28(P). i am getting the phone number if the app is open at the time of call, but otherwise number is coming as blank.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
phnNbr = intent?.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER).toString()
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P && Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
val telephony =
context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
telephony.listen(object : PhoneStateListener() {
override fun onCallStateChanged(state: Int, incomingNumber: String) {
super.onCallStateChanged(state, incomingNumber)
println("incomingNumber API>28: $incomingNumber")
phnNbr = incomingNumber
}
}, PhoneStateListener.LISTEN_CALL_STATE)
}
I was using onCallStateChanged as i learned from the documentation that the getStringExtra(EXTRA_INCOMING_NUMBER)
is deprecated in SDK<= Android P. But to my surprise, as I had READ_PHONE_NUMBERS & READ_CALL_LOG permissions, the old way getStringExtra(EXTRA_INCOMING_NUMBER)
worked for me and this also solved wrong responses when operating Sim 2. Just be sure to handle multiple calls to fun onReceive
of the BroadcastReceiver.