'telephony.listen , phoneStateListener not working when app is closed

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)
            }


Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 A Farmanbar