0

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)
            }
Rauson Ali
  • 111
  • 10

2 Answers2

2

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.

Rauson Ali
  • 111
  • 10
1

It is normal behavior for Android OS to protect user privacy against malicious apps from stealing user information. However, You can resolve the problem by using a System Event Broadcast Receiver to be notified of incoming phone calls. Here is a good example to follow. The example is not enough and applicable for current android API levels and you need to have a Foreground Service when a call is received then run the Foreground Service and execute your codes.

A Farmanbar
  • 4,381
  • 5
  • 24
  • 42