在搭载 Android 10(API 级别 29)或更高版本的设备上,您的应用可以将来自用户通讯簿中没有的号码的来电识别为潜在骚扰电话。用户可以选择静默拒接骚扰电话。为了让用户更清楚地了解自己错过的来电,系统会在通话记录中记录这些被屏蔽的来电的相关信息。使用 Android 10 API 后,您无需从用户处获取 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. } } } } }
将 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)
您必须在清单文件中注册 CallScreeningService 实现,并指定适当的 intent 过滤器和权限,以便系统能够正确触发它。
<service
android:name=".ScreeningService"
android:permission="android.permission.BIND_SCREENING_SERVICE">
<intent-filter>
<action android:name="android.telecom.CallScreeningService" />
</intent-filter>
</service>