過濾電話

在搭載 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 實作,並設定適當的意圖篩選器和權限,系統才能正確觸發。

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