PhoneStateListener's onCallStateChanged took the state of the phone call and the number being called as parameters:
val telephonyManager =
context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
telephonyManager.listen(
object : PhoneStateListener() {
override fun onCallStateChanged(state: Int, phoneNumber: String) {
super.onCallStateChanged(state, phoneNumber)
}
},
PhoneStateListener.LISTEN_CALL_STATE
)
After the deprecation of listen() and PhoneStateListener, the suggested way to listen to phone calls is through registerTelephonyCallback(), that takes an Executor and a TelephonyCallback as parameters, the problem is that TelephonyCallback.CallStateListener's onCallStateChanged only takes the call state as parameter:
telephonyManager.registerTelephonyCallback(
context.mainExecutor,
object : TelephonyCallback(), TelephonyCallback.CallStateListener {
override fun onCallStateChanged(state: Int) {
// WHERE IS PHONE NUMBER?
}
}
)
I absolutely need to know the phone number being called in order to make my app work properly.
Does someone know how to obtain it using TelephonyCallback or, at least, without using deprecated methods?
I solved it using
CallScreeningService, that is available from API 24, but unusable until API 29 because ofcallDirection:In order to use this, your app has to become the default one for call screening:
I don't know if you can access any other information about the call besides the phone number, I currently save the phone number in SharedPreferences and then access it in the new
PhoneStateListener'sonCallStateChanged.As I said before, this solution is only possible from API 29, for lower API versions you have to use the deprecated way, I think is the only one to achieve this.