搭載 Android 10 以上版本的裝置管理通話意圖的方式,與搭載 Android 9 以下版本的裝置不同。在 Android 10 以上版本中,ACTION_NEW_OUTGOING_CALL 廣播已淘汰,並由 CallRedirectionService API 取代。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() } } } }
您必須在資訊清單中註冊這項服務,系統才能正確啟動。
<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 : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 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 } }