Перенаправить вызов
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Устройства под управлением Android 10 или более поздней версии управляют намерениями вызова иначе, чем устройства под управлением Android 9 или более ранней версии. В Android 10 и более поздних версиях широковещательная рассылка ACTION_NEW_OUTGOING_CALL
устарела и заменена API CallRedirectionService
. CallRedirectionService
предоставляет интерфейсы, которые можно использовать для изменения исходящих вызовов, совершаемых платформой Android. Например, сторонние приложения могут отменять вызовы и перенаправлять их через VoIP.
Котлин
class RedirectionService : CallRedirectionService() {
override fun onPlaceCall(
handle: Uri,
initialPhoneAccount: PhoneAccountHandle,
allowInteractiveResponse: Boolean
) {
// Determine if the call should proceed, be redirected, or cancelled.
val callShouldProceed = true
val callShouldRedirect = false
when {
callShouldProceed -> {
placeCallUnmodified()
}
callShouldRedirect -> {
// Update the URI to point to a different phone number or modify the
// PhoneAccountHandle and redirect.
redirectCall(handle, initialPhoneAccount, true)
}
else -> {
cancelCall()
}
}
}
}
Ява
class RedirectionService extends CallRedirectionService {
@Override
public void onPlaceCall(
@NonNull Uri handle,
@NonNull PhoneAccountHandle initialPhoneAccount,
boolean allowInteractiveResponse
) {
// Determine if the call should proceed, be redirected, or cancelled.
// Your app should implement this logic to determine the redirection.
boolean callShouldProceed = true;
boolean callShouldRedirect = false;
if (callShouldProceed) {
placeCallUnmodified();
} else if (callShouldRedirect) {
// Update the URI to point to a different phone number or modify the
// PhoneAccountHandle and redirect.
redirectCall(handle, initialPhoneAccount, true);
} else {
cancelCall();
}
}
}
Вы должны зарегистрировать эту службу в манифесте, чтобы система могла правильно ее запустить.
<service
android:name=".RedirectionService"
android:permission="android.permission.BIND_CALL_REDIRECTION_SERVICE">
<intent-filter>
<action android:name="android.telecom.CallRedirectionService"/>
</intent-filter>
</service>
Чтобы использовать службу перенаправления, ваше приложение должно запросить роль перенаправления вызовов у RoleManager
. При этом пользователю будет задан вопрос, хотят ли они разрешить вашему приложению обрабатывать перенаправления вызовов. Если вашему приложению не предоставлена эта роль, ваша служба перенаправления не используется.
Вам следует проверить, имеет ли ваше приложение эту роль, когда пользователь запускает ваше приложение, чтобы вы могли запросить его при необходимости. Вы запускаете намерение, созданное RoleManager
, поэтому убедитесь, что вы переопределили функцию onActivityResult()
для обработки выбора пользователя.
Котлин
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Tell the system that you want your app to handle call redirects. This
// is done by using the RoleManager to register your app to handle redirects.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
val roleManager = getSystemService(Context.ROLE_SERVICE) as RoleManager
// Check if the app needs to register call redirection role.
val shouldRequestRole = roleManager.isRoleAvailable(RoleManager.ROLE_CALL_REDIRECTION) &&
!roleManager.isRoleHeld(RoleManager.ROLE_CALL_REDIRECTION)
if (shouldRequestRole) {
val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_REDIRECTION)
startActivityForResult(intent, REDIRECT_ROLE_REQUEST_CODE)
}
}
}
companion object {
private const val REDIRECT_ROLE_REQUEST_CODE = 1
}
}
Ява
class MainActivity extends AppCompatActivity {
private static final int REDIRECT_ROLE_REQUEST_CODE = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Tell the system that you want your app to handle call redirects. This
// is done by using the RoleManager to register your app to handle redirects.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
RoleManager roleManager = (RoleManager) getSystemService(Context.ROLE_SERVICE);
// Check if the app needs to register call redirection role.
boolean shouldRequestRole = roleManager.isRoleAvailable(RoleManager.ROLE_CALL_REDIRECTION) &&
!roleManager.isRoleHeld(RoleManager.ROLE_CALL_REDIRECTION);
if (shouldRequestRole) {
Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_REDIRECTION);
startActivityForResult(intent, REDIRECT_ROLE_REQUEST_CODE);
}
}
}
}
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-29 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-07-29 UTC."],[],[],null,["# Redirect a call\n\nDevices that run Android 10 or higher manage call intents differently than\ndevices that run Android 9 or lower. On Android 10 and higher, the\n[`ACTION_NEW_OUTGOING_CALL`](/reference/android/content/Intent#ACTION_NEW_OUTGOING_CALL)\nbroadcast is deprecated and replaced with the\n[`CallRedirectionService`](/reference/android/telecom/CallRedirectionService)\nAPI. The `CallRedirectionService` provides interfaces for you to use to\nmodify outgoing calls made by the Android platform. For example, third-party\napps might cancel calls and reroute them over VoIP. \n\n### Kotlin\n\n```kotlin\nclass RedirectionService : CallRedirectionService() {\n override fun onPlaceCall(\n handle: Uri,\n initialPhoneAccount: PhoneAccountHandle,\n allowInteractiveResponse: Boolean\n ) {\n // Determine if the call should proceed, be redirected, or cancelled.\n val callShouldProceed = true\n val callShouldRedirect = false\n when {\n callShouldProceed -\u003e {\n placeCallUnmodified()\n }\n callShouldRedirect -\u003e {\n // Update the URI to point to a different phone number or modify the\n // PhoneAccountHandle and redirect.\n redirectCall(handle, initialPhoneAccount, true)\n }\n else -\u003e {\n cancelCall()\n }\n }\n }\n}\n```\n\n### Java\n\n```java\nclass RedirectionService extends CallRedirectionService {\n @Override\n public void onPlaceCall(\n @NonNull Uri handle,\n @NonNull PhoneAccountHandle initialPhoneAccount,\n boolean allowInteractiveResponse\n ) {\n // Determine if the call should proceed, be redirected, or cancelled.\n // Your app should implement this logic to determine the redirection.\n boolean callShouldProceed = true;\n boolean callShouldRedirect = false;\n if (callShouldProceed) {\n placeCallUnmodified();\n } else if (callShouldRedirect) {\n // Update the URI to point to a different phone number or modify the\n // PhoneAccountHandle and redirect.\n redirectCall(handle, initialPhoneAccount, true);\n } else {\n cancelCall();\n }\n }\n}\n```\n\nYou must register this service in the manifest so the system can start it\ncorrectly. \n\n \u003cservice\n android:name=\".RedirectionService\"\n android:permission=\"android.permission.BIND_CALL_REDIRECTION_SERVICE\"\u003e\n \u003cintent-filter\u003e\n \u003caction android:name=\"android.telecom.CallRedirectionService\"/\u003e\n \u003c/intent-filter\u003e\n \u003c/service\u003e\n\nTo use a redirection service, your app must request the call redirection role\nfrom the [`RoleManager`](/reference/android/app/role/RoleManager). This will ask\nthe user if they want to allow your app to handle call redirects. If your app\nisn't granted this role, your redirection service isn't used.\n\nYou should check if your app has this role when the user launches your app so\nyou can request it as needed. You launch an intent created by the `RoleManager`,\nso ensure you override the\n[`onActivityResult()`](/reference/android/app/Activity#onActivityResult(int,%20int,%20android.content.Intent))\nfunction to handle the user's selection. \n\n### Kotlin\n\n```kotlin\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n\n // Tell the system that you want your app to handle call redirects. This\n // is done by using the RoleManager to register your app to handle redirects.\n if (android.os.Build.VERSION.SDK_INT \u003e= android.os.Build.VERSION_CODES.Q) {\n val roleManager = getSystemService(Context.ROLE_SERVICE) as RoleManager\n // Check if the app needs to register call redirection role.\n val shouldRequestRole = roleManager.isRoleAvailable(RoleManager.ROLE_CALL_REDIRECTION) &&\n !roleManager.isRoleHeld(RoleManager.ROLE_CALL_REDIRECTION)\n if (shouldRequestRole) {\n val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_REDIRECTION)\n startActivityForResult(intent, REDIRECT_ROLE_REQUEST_CODE)\n }\n }\n }\n\n companion object {\n private const val REDIRECT_ROLE_REQUEST_CODE = 1\n }\n}\n```\n\n### Java\n\n```java\nclass MainActivity extends AppCompatActivity {\n private static final int REDIRECT_ROLE_REQUEST_CODE = 0;\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n // Tell the system that you want your app to handle call redirects. This\n // is done by using the RoleManager to register your app to handle redirects.\n if (android.os.Build.VERSION.SDK_INT \u003e= android.os.Build.VERSION_CODES.Q) {\n RoleManager roleManager = (RoleManager) getSystemService(Context.ROLE_SERVICE);\n // Check if the app needs to register call redirection role.\n boolean shouldRequestRole = roleManager.isRoleAvailable(RoleManager.ROLE_CALL_REDIRECTION) &&\n !roleManager.isRoleHeld(RoleManager.ROLE_CALL_REDIRECTION);\n if (shouldRequestRole) {\n Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_REDIRECTION);\n startActivityForResult(intent, REDIRECT_ROLE_REQUEST_CODE);\n }\n }\n }\n}\n```"]]