Search code examples
androidkotlinbroadcastreceivertelephony

How to get phone number from an incoming call from Android 12?


I need to get phonenumber from incoming call it works well below Android 12 device with this method

val number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)

but for Android 12 and above device (TelephonyManager.EXTRA_INCOMING_NUMBER) data is not available in intent.

Manifest permission is not issue I can add any permission if required. I've added this permission in my manifest

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_CALL_LOG" />
    <uses-permission android:name="android.permission.WRITE_CALL_LOG" />

I've also tried contentResolver query but it gives second last number data in cursor not current incoming call data.

val cancellationSignal = CancellationSignal()
val cursor = context.contentResolver.query(
    CallLog.Calls.CONTENT_URI,
    null,
    CallLog.Calls.TYPE + " = ?",
    arrayOf(CallLog.Calls.INCOMING_TYPE.toString()),
    CallLog.Calls.DATE + " DESC",
    cancellationSignal
)
if (cursor != null && cursor.moveToFirst()) {
    val indexNumber = cursor.getColumnIndex(CallLog.Calls.NUMBER)
    val number = cursor.getString(indexNumber)
    print(number)
    cancellationSignal.cancel()
    cursor.close()
}

Does anyone know How to find number for Android 12 and above device?


Solution

  • try this in Call.Details

     private fun extractPhoneNumber(callDetails: Call.Details): String? {
        val handle = callDetails.handle
        if (handle != null) {
            // Attempt to extract phone number from the handle
            return handle.schemeSpecificPart
        } else {
            // Handle is null, try other methods if available
            val gatewayInfo = callDetails.gatewayInfo
            if (gatewayInfo != null) {
                return gatewayInfo.originalAddress.schemeSpecificPart
            }
        }
        return null
    }