To be honest, I've searched a lot on the subject, but since is a lot of changes on latest API it is still not clear for me if it is possible somehow to get the phone number of the caller.
The main idea is have service, which uses TelephonyCallBack class
object : TelephonyCallback(), TelephonyCallback.CallStateListener {
override fun onCallStateChanged(state: Int) {
when (state) {
TelephonyManager.CALL_STATE_RINGING -> {
Log.d("incCall", "Incoming call detected") // <-- here I need to get the number
}
TelephonyManager.CALL_STATE_OFFHOOK -> {
Log.d("incCall", "Call answered")
}
TelephonyManager.CALL_STATE_IDLE -> {
Log.d("incCall", "Call ended")
}
}
}
}
Any suggestions or resources would be great, Thanks
Add READ_PHONE_STATE and READ_CALL_LOG permissions in the AndroidManifest.xml
like this
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
Create a Receiver class which extends BroadcastReceiver to listen to incoming call events
class IncomingCallReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == TelephonyManager.ACTION_PHONE_STATE_CHANGED) {
val state = intent.getStringExtra(TelephonyManager.EXTRA_STATE)
if (state == TelephonyManager.EXTRA_STATE_RINGING) {
val incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)
Log.d("IncomingCallReceiver", "Incoming number: $incomingNumber")
}
}
}
}
Register the reciever in the onCreate method of Activity
registerReceiver(IncomingCallReceiver(), IntentFilter("android.intent.action.PHONE_STATE"), RECEIVER_EXPORTED)