Filtrar llamadas

Los dispositivos que ejecutan Android 10 (nivel de API 29) o versiones posteriores permiten que tu app identifique llamadas de números que no están en la libreta de direcciones del usuario como posibles llamadas de spam. Los usuarios pueden elegir que se rechacen las llamadas de spam de manera silenciosa. Para brindar una mayor transparencia a los usuarios cuando pierden una llamada, la información sobre las llamadas bloqueadas se registra en el registro de llamadas. El uso de la API de Android 10 elimina la necesidad de obtener el permiso READ_CALL_LOG del usuario para proporcionar la funcionalidad de identificador de llamadas y número de llamada.

Usas una implementación de CallScreeningService para filtrar llamadas. Llama a la función onScreenCall() para las llamadas entrantes o salientes nuevas cuando el número no esté en la lista de contactos del usuario. Puedes verificar el objeto Call.Details para obtener información sobre la llamada. Específicamente, la función getCallerNumberVerificationStatus() incluye información del proveedor de red sobre el otro número. Si el estado de verificación falló, esta es una buena indicación de que la llamada proviene de un número no válido o de una posible llamada de spam.

Kotlin

class ScreeningService : CallScreeningService() {
    // This function is called when an ingoing or outgoing call
    // is from a number not in the user's contacts list
    override fun onScreenCall(callDetails: Call.Details) {
        // Can check the direction of the call
        val isIncoming = callDetails.callDirection == Call.Details.DIRECTION_INCOMING

        if (isIncoming) {
            // the handle (e.g. phone number) that the Call is currently connected to
            val handle: Uri = callDetails.handle

            // determine if you want to allow or reject the call
            when (callDetails.callerNumberVerificationStatus) {
                Connection.VERIFICATION_STATUS_FAILED -> {
                    // Network verification failed, likely an invalid/spam call.
                }
                Connection.VERIFICATION_STATUS_PASSED -> {
                    // Network verification passed, likely a valid call.
                }
                else -> {
                    // Network could not perform verification.
                    // This branch matches Connection.VERIFICATION_STATUS_NOT_VERIFIED.
                }
            }
        }
    }
}

Java

class ScreeningService extends CallScreeningService {
    @Override
    public void onScreenCall(@NonNull Call.Details callDetails) {
        boolean isIncoming = callDetails.getCallDirection() == Call.Details.DIRECTION_INCOMING;

        if (isIncoming) {
            Uri handle = callDetails.getHandle();

            switch (callDetails.getCallerNumberVerificationStatus()) {
                case Connection.VERIFICATION_STATUS_FAILED:
                    // Network verification failed, likely an invalid/spam call.
                    break;
                case Connection.VERIFICATION_STATUS_PASSED:
                    // Network verification passed, likely a valid call.
                    break;
                default:
                    // Network could not perform verification.
                    // This branch matches Connection.VERIFICATION_STATUS_NOT_VERIFIED
            }
        }
    }
}

Configura la función onScreenCall() para que llame a respondToCall() y le indique al sistema cómo responder la llamada nueva. Esta función toma un parámetro CallResponse que puedes usar para indicarle al sistema que bloquee la llamada, la rechace como si el usuario lo hiciera o la silencie. También puedes indicarle al sistema que omita por completo agregar esta llamada al registro de llamadas del dispositivo.

Kotlin

// Tell the system how to respond to the incoming call
// and if it should notify the user of the call.
val response = CallResponse.Builder()
    // Sets whether the incoming call should be blocked.
    .setDisallowCall(false)
    // Sets whether the incoming call should be rejected as if the user did so manually.
    .setRejectCall(false)
    // Sets whether ringing should be silenced for the incoming call.
    .setSilenceCall(false)
    // Sets whether the incoming call should not be displayed in the call log.
    .setSkipCallLog(false)
    // Sets whether a missed call notification should not be shown for the incoming call.
    .setSkipNotification(false)
    .build()

// Call this function to provide your screening response.
respondToCall(callDetails, response)

Java

// Tell the system how to respond to the incoming call
// and if it should notify the user of the call.
CallResponse.Builder response = new CallResponse.Builder();
// Sets whether the incoming call should be blocked.
response.setDisallowCall(false);
// Sets whether the incoming call should be rejected as if the user did so manually.
response.setRejectCall(false);
// Sets whether ringing should be silenced for the incoming call.
response.setSilenceCall(false);
// Sets whether the incoming call should not be displayed in the call log.
response.setSkipCallLog(false);
// Sets whether a missed call notification should not be shown for the incoming call.
response.setSkipNotification(false);

// Call this function to provide your screening response.
respondToCall(callDetails, response.build());

Debes registrar la implementación de CallScreeningService en el archivo de manifiesto con el filtro de intents y el permiso apropiados para que el sistema pueda activarla correctamente.

<service
    android:name=".ScreeningService"
    android:permission="android.permission.BIND_SCREENING_SERVICE">
    <intent-filter>
        <action android:name="android.telecom.CallScreeningService" />
    </intent-filter>
</service>