Filtrar chamadas

Dispositivos com o Android 10 (nível 29 da API) ou versões mais recentes permitem que o app identifique chamadas de números que não estão no catálogo de endereços do usuário como possíveis chamadas de spam. Os usuários podem rejeitar chamadas de spam silenciosamente. Para oferecer maior transparência aos usuários quando eles perdem chamadas, as informações sobre essas chamadas bloqueadas são registradas no registro de chamadas. O uso da API do Android 10 elimina a necessidade de receber a permissão READ_CALL_LOG do usuário para fornecer os recursos de filtro de ligações e identificador de chamadas.

Use uma implementação de CallScreeningService para filtrar chamadas. Chame a função onScreenCall() para todas as novas chamadas recebidas ou realizadas quando o número não estiver na lista de contatos do usuário. Você pode verificar o objeto Call.Details para ver informações sobre a chamada. Especificamente, a função getCallerNumberVerificationStatus() inclui informações da provedora de rede sobre o outro número. Se o status de verificação falhou, essa é uma boa indicação de que a chamada é de um número inválido ou uma possível chamada 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
            }
        }
    }
}

Defina a função onScreenCall() para chamar respondToCall() e informar ao sistema como responder à nova chamada. Essa função recebe um parâmetro CallResponse que pode ser usado para instruir o sistema a bloquear a chamada, rejeitá-la como se o usuário tivesse feito isso ou silenciá-la. Também é possível dizer ao sistema para pular completamente a adição dessa chamada ao registro de chamadas do 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());

É necessário registrar a implementação CallScreeningService no arquivo de manifesto com o filtro de intent e a permissão adequados para que o sistema possa acioná-lo corretamente.

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