Экранные вызовы
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Устройства под управлением Android 10 (уровень API 29) или выше позволяют вашему приложению идентифицировать звонки с номеров, которых нет в адресной книге пользователя, как потенциальные спам-вызовы. Пользователи могут выбрать автоматическое отклонение спам-вызовов. Чтобы обеспечить большую прозрачность для пользователей в случае пропуска вызовов, информация об этих заблокированных вызовах записывается в журнал вызовов. Использование API Android 10 устраняет необходимость получения разрешения READ_CALL_LOG
от пользователя для обеспечения функции фильтрации вызовов и идентификации вызывающего абонента.
Вы используете реализацию CallScreeningService
для проверки вызовов. Вызовите функцию onScreenCall()
для любых новых входящих или исходящих вызовов, если номер отсутствует в списке контактов пользователя. Вы можете проверить объект Call.Details
для получения информации о вызове. В частности, функция getCallerNumberVerificationStatus()
включает информацию от поставщика сети о другом номере. Если статус проверки не пройден, это верный признак того, что звонок поступил с неверного номера или что это потенциальный спам-вызов.
Котлин
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.
}
}
}
}
}
Ява
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
}
}
}
}
Настройте функцию onScreenCall()
для вызова respondToCall()
, чтобы сообщить системе, как реагировать на новый вызов. Эта функция принимает параметр CallResponse
, который вы можете использовать, чтобы указать системе заблокировать вызов, отклонить его, как если бы это сделал пользователь, или отключить его. Вы также можете указать системе вообще не добавлять этот вызов в журнал вызовов устройства.
Котлин
// 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)
Ява
// 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());
Вы должны зарегистрировать реализацию CallScreeningService
в файле манифеста с соответствующим фильтром намерений и разрешением, чтобы система могла правильно активировать ее.
<service
android:name=".ScreeningService"
android:permission="android.permission.BIND_SCREENING_SERVICE">
<intent-filter>
<action android:name="android.telecom.CallScreeningService" />
</intent-filter>
</service>
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons "С указанием авторства 4.0", а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-08-28 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-08-28 UTC."],[],[],null,["Devices that run Android 10 (API level 29) or higher allow your app to identify\ncalls from numbers that aren't in the user's address book as potential spam\ncalls. Users can choose to have spam calls silently rejected. To provide greater\ntransparency to users when they miss calls, information about these blocked\ncalls is logged in the call log. Using the Android 10 API eliminates the\nrequirement to obtain the\n[`READ_CALL_LOG`](/reference/android/Manifest.permission#READ_CALL_LOG)\npermission from the user in order to provide call screening and caller ID\nfunctionality.\n\nYou use a\n[`CallScreeningService`](/reference/android/telecom/CallScreeningService)\nimplementation to screen calls. Call the\n[`onScreenCall()`](/reference/android/telecom/CallScreeningService#onScreenCall(android.telecom.Call.Details))\nfunction for any new incoming or outgoing calls when the number is not in the\nuser's contact list. You can check the\n[`Call.Details`](/reference/android/telecom/Call.Details) object for information\nabout the call. Specifically, the\n[`getCallerNumberVerificationStatus()`](/reference/android/telecom/Call.Details#getCallerNumberVerificationStatus())\nfunction includes information from the network provider about the other number.\nIf the verification status failed, this is a good indication that the call is\nfrom an invalid number or a potential spam call. \n\nKotlin \n\n```kotlin\nclass ScreeningService : CallScreeningService() {\n // This function is called when an ingoing or outgoing call\n // is from a number not in the user's contacts list\n override fun onScreenCall(callDetails: Call.Details) {\n // Can check the direction of the call\n val isIncoming = callDetails.callDirection == Call.Details.DIRECTION_INCOMING\n\n if (isIncoming) {\n // the handle (e.g. phone number) that the Call is currently connected to\n val handle: Uri = callDetails.handle\n\n // determine if you want to allow or reject the call\n when (callDetails.callerNumberVerificationStatus) {\n Connection.VERIFICATION_STATUS_FAILED -\u003e {\n // Network verification failed, likely an invalid/spam call.\n }\n Connection.VERIFICATION_STATUS_PASSED -\u003e {\n // Network verification passed, likely a valid call.\n }\n else -\u003e {\n // Network could not perform verification.\n // This branch matches Connection.VERIFICATION_STATUS_NOT_VERIFIED.\n }\n }\n }\n }\n}\n```\n\nJava \n\n```java\nclass ScreeningService extends CallScreeningService {\n @Override\n public void onScreenCall(@NonNull Call.Details callDetails) {\n boolean isIncoming = callDetails.getCallDirection() == Call.Details.DIRECTION_INCOMING;\n\n if (isIncoming) {\n Uri handle = callDetails.getHandle();\n\n switch (callDetails.getCallerNumberVerificationStatus()) {\n case Connection.VERIFICATION_STATUS_FAILED:\n // Network verification failed, likely an invalid/spam call.\n break;\n case Connection.VERIFICATION_STATUS_PASSED:\n // Network verification passed, likely a valid call.\n break;\n default:\n // Network could not perform verification.\n // This branch matches Connection.VERIFICATION_STATUS_NOT_VERIFIED\n }\n }\n }\n}\n```\n\nSet the `onScreenCall()` function to call\n[`respondToCall()`](/reference/android/telecom/CallScreeningService#respondToCall(android.telecom.Call.Details,%20android.telecom.CallScreeningService.CallResponse))\nto tell the system how to respond to the new call. This function takes a\n[`CallResponse`](/reference/android/telecom/CallScreeningService.CallResponse)\nparameter that you can use to tell the system to block the call, reject it as if\nthe user did, or silence it. You can also tell the system to skip adding this\ncall to the device's call log altogether. \n\nKotlin \n\n```kotlin\n// Tell the system how to respond to the incoming call\n// and if it should notify the user of the call.\nval response = CallResponse.Builder()\n // Sets whether the incoming call should be blocked.\n .setDisallowCall(false)\n // Sets whether the incoming call should be rejected as if the user did so manually.\n .setRejectCall(false)\n // Sets whether ringing should be silenced for the incoming call.\n .setSilenceCall(false)\n // Sets whether the incoming call should not be displayed in the call log.\n .setSkipCallLog(false)\n // Sets whether a missed call notification should not be shown for the incoming call.\n .setSkipNotification(false)\n .build()\n\n// Call this function to provide your screening response.\nrespondToCall(callDetails, response)\n```\n\nJava \n\n```java\n// Tell the system how to respond to the incoming call\n// and if it should notify the user of the call.\nCallResponse.Builder response = new CallResponse.Builder();\n// Sets whether the incoming call should be blocked.\nresponse.setDisallowCall(false);\n// Sets whether the incoming call should be rejected as if the user did so manually.\nresponse.setRejectCall(false);\n// Sets whether ringing should be silenced for the incoming call.\nresponse.setSilenceCall(false);\n// Sets whether the incoming call should not be displayed in the call log.\nresponse.setSkipCallLog(false);\n// Sets whether a missed call notification should not be shown for the incoming call.\nresponse.setSkipNotification(false);\n\n// Call this function to provide your screening response.\nrespondToCall(callDetails, response.build());\n```\n\nYou must register the `CallScreeningService` implementation in the manifest\nfile with the appropriate intent filter and permission so the system can trigger\nit correctly. \n\n \u003cservice\n android:name=\".ScreeningService\"\n android:permission=\"android.permission.BIND_SCREENING_SERVICE\"\u003e\n \u003cintent-filter\u003e\n \u003caction android:name=\"android.telecom.CallScreeningService\" /\u003e\n \u003c/intent-filter\u003e\n \u003c/service\u003e"]]