如要將傳入的 DeepLinkRequest 執行個體對應至可新增至應用程式返回堆疊的鍵,請定義 DeepLinkMatcher 執行個體。
DeepLinkMatcher 是抽象類別,包含 match 和 matchRequest 兩種方法。子類別必須實作 matchRequest,該方法會接收 DeepLinkRequest,並在要求相符時傳回 DeepLinkMatcher.MatchResult,否則傳回 null。
因為單一要求可能有多個比對器相符,MatchResult 會實作 Comparable 來排列結果,並選取最相符的結果。
型別參數
DeepLinkMatcher 類別會宣告兩個泛型參數:
DeepLinkMatcher<T : Any, R : DeepLinkMatcher.MatchResult<T>>。
T : Any:深層連結相符時傳回的目的地導覽鍵類型 (例如UserProfileKey或NavKey)。R : DeepLinkMatcher.MatchResult<T>:matchRequest和match傳回的特定MatchResult子類型。
第二個型別參數 R 會保留專門的相符資訊,且不需要未檢查的向下轉換:
StaticKeyDeepLinkMatcher將R繫結至DeepLinkMatcher.MatchResult<T>。UriDeepLinkMatcher會將R繫結至UriMatchResult,並保留剖析的路徑和查詢引數,以及模式比對分數。BackStackMatcher會將R繫結至BackStackMatchResult,並保留withBackStack建構的合成返回堆疊清單。
預先篩選要求
DeepLinkMatcher 實作可以指定 DeepLinkMatcher.Filter 執行個體清單,在評估要求前先進行篩選。
程式庫包含用於建立常見篩選器的輔助函式:
DeepLinkMatcher.mimeTypeFilter:依據確切mimeType字串比對 (檢查MimeTypeExtrasKey)。DeepLinkMatcher.actionFilter:比對完全相符的action字串 (檢查ActionExtrasKey)。
這個方法可讓您針對不同動作重複使用相同的 URI 模式,例如檢視與編輯:
val viewFilter = DeepLinkMatcher.actionFilter(Intent.ACTION_VIEW) val editFilter = DeepLinkMatcher.actionFilter(Intent.ACTION_EDIT) val imageUriPattern = DeepLinkUri("www.example.com/image/{id}") val viewMatcher = UriDeepLinkMatcher(imageUriPattern, serializer<Gallery>(), filters = listOf(viewFilter)) val editMatcher = UriDeepLinkMatcher(imageUriPattern, serializer<Editor>(), filters = listOf(editFilter))
由於 Filter 是功能性 (SAM) 介面,您也可以使用 lambda 運算式建立篩選器:
val myFilter = DeepLinkMatcher.Filter { request -> request.uri != null }
使用提供的比對器
程式庫包含三種標準 DeepLinkMatcher 實作方式:StaticKeyDeepLinkMatcher、UriDeepLinkMatcher 和 BackStackMatcher。如果這些比對器不符合應用程式需求,您可以建立自訂深層連結比對器。
比對基本深層連結
對於沒有要擷取引數的基本深層連結,請使用 StaticKeyDeepLinkMatcher 比對符合所有指定篩選條件的請求。
舉例來說,如要處理 ACTION_APPLICATION_PREFERENCES 的意圖:
val preferencesActionFilter = DeepLinkMatcher.actionFilter(Intent.ACTION_APPLICATION_PREFERENCES) val preferencesActionDeepLinkMatcher = StaticKeyDeepLinkMatcher(PreferencesScreen, listOf(preferencesActionFilter))
比對 URI 深層連結
如要根據模式比對階層式 URI 並擷取引數,請使用 UriDeepLinkMatcher。舉例來說,您可以比對 www.example.com/users/{id},將 id 引數擷取至目的地鍵。詳情請參閱「比對 URI 深層連結」。
建構合成返回堆疊
如要定義如何從相符的項目建構合成返回堆疊,請使用 BackStackMatcher。請勿直接例項化 BackStackMatcher,而是呼叫其他 DeepLinkMatcher 的 withBackStack 擴充函式。withBackStack 會將接收器包裝在 BackStackMatcher 中,該
會傳回包含合成返回堆疊 List 的 BackStackMatchResult。由於 BackStackMatchResult 會將比較作業委派給基礎比對結果,因此在 withBackStack 中包裝比對器會保留原始比對排名。
val homeMatcher = StaticKeyDeepLinkMatcher(HomeKey, listOf(DeepLinkMatcher.actionFilter(Intent.ACTION_VIEW))) val userListMatcher = UriDeepLinkMatcher( DeepLinkUri("www.example.com/users?page={page}"), serializer<UserListKey>() ).withBackStack { matchResult -> listOf(HomeKey, matchResult.key) } val userProfileMatcher = UriDeepLinkMatcher( DeepLinkUri("www.example.com/users/{id}"), serializer<UserProfileKey>() ).withBackStack { matchResult -> listOf(HomeKey, UserListKey(), matchResult.key) }
如要在活動中處理產生的返回堆疊,請參閱「比對傳入的要求」。