如要將傳入的 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。請在另一個 DeepLinkMatcher 上呼叫 withBackStack 擴充功能函式,而非直接例項化 BackStackMatcher。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) }
如要處理 Activity 中產生的返回堆疊,請參閱「比對傳入要求」。