버전 1.2.0부터 Navigation 3은 DeepLinkRequest
DeepLinkMatcher 클래스를 사용하여
앱의 대상으로 딥 링크를 지원합니다.
앱에서 딥 링크를 지원하려면 다음 단계를 완료하세요.
AndroidManifest.xml에서 인텐트 필터를 정의 하여 앱에서 처리할 수 있는 URI를 지정합니다.DeepLinkMatcher인스턴스를 만듭니다. 수신 요청을 탐색 키에 매핑합니다.- 활동의
onCreate또는onNewIntent메서드에서 수신 요청을 일치 시키고 백 스택을 적절히 업데이트합니다.
DeepLinkRequest 만들기
DeepLinkRequest는 수신 딥 링크를 나타냅니다. 인텐트 작업 또는 MIME 유형과 같은 추가 정보가 포함된
DeepLinkUri 및 선택적 RequestExtras가 포함되어 있습니다.
// Create a request with a String URI val request = DeepLinkRequest(uri = "https://www.example.com/home") // Create a request from a DeepLinkUri val deepLinkUri = DeepLinkUri("https://www.example.com/home") val requestFromUri = DeepLinkRequest(uri = deepLinkUri) // Create a request with a URI and action val requestWithAction = DeepLinkRequest( uri = "https://www.example.com/home", extras = DeepLinkRequest.actionExtra("android.intent.action.VIEW") ) // Create a request with URI, action and mimeType val requestWithMimeType = DeepLinkRequest( uri = "https://www.example.com/image", extras = requestExtras { put(DeepLinkRequest.ActionExtrasKey, "android.intent.action.VIEW") put(DeepLinkRequest.Companion.MimeTypeExtrasKey, "image/png") } )
DeepLinkRequest 추가 제공
딥 링크와 관련된 추가 정보를 저장하려면
RequestExtras 클래스를 사용하세요. 추가 정의 및 인스턴스화를 유형 안전하게 만들려면
라이브러리에서 RequestExtrasKey 인터페이스 및
requestExtras DSL을 제공합니다.
또한 라이브러리는 두 개의 추가 키와 연결된 도우미를 제공합니다.
MimeTypeExtrasKey: MIME 유형String을 저장하는 데 사용됩니다.ActionExtrasKey(Android 전용):Intent의 작업String을 저장하는 데 사용됩니다.
val extras: RequestExtras = requestExtras { put(DeepLinkRequest.Companion.MimeTypeExtrasKey, "application/json") put(DeepLinkRequest.ActionExtrasKey, Intent.ACTION_VIEW) } // Access typed values using the get operator val mimeType: String? = extras[DeepLinkRequest.Companion.MimeTypeExtrasKey] val action: String? = extras[DeepLinkRequest.ActionExtrasKey] // Create extras using helper functions and combine them val mimeTypeExtras: RequestExtras = DeepLinkRequest.mimeTypeExtra("application/json") val combinedExtras: RequestExtras = extras + DeepLinkRequest.actionExtra(Intent.ACTION_VIEW)
자체 맞춤 추가를 정의하려면 유형화된 일반으로 RequestExtrasKey
인터페이스를 구현합니다.
// Define a custom typed key: object CampaignIdExtrasKey : RequestExtrasKey<String> val customExtras: RequestExtras = requestExtras { put(CampaignIdExtrasKey, "123") } val campaignId: String? = customExtras[CampaignIdExtrasKey]
emptyRequestExtras()를 사용하여 빈 인스턴스를 구성하거나
+ (plus) 및 - (minus) 연산자를 사용하여 추가를 결합할 수도 있습니다.
Intent에서 DeepLinkRequest 만들기
Android에서는 Intent에서 직접 DeepLinkRequest를 만들 수 있습니다. 이 방법으로 구성하면 DeepLinkRequest가 다음과 같이 빌드됩니다.
uri는 인텐트의data필드에서 복사됩니다.- null이 아닌 경우 MIME 유형 및 작업 추가는 상응하는 인텐트 필드에서 설정됩니다.
- null이 아닌 값이 있는 모든
intent.extras는DeepLinkRequest.IntentExtrasKey에SavedState로 저장됩니다. extras매개변수를 사용하여 제공된 추가 추가가 추가됩니다.
object CampaignIdExtrasKey : RequestExtrasKey<String> val intent = Intent(Intent.ACTION_VIEW).apply { data = Uri.parse("https://www.example.com/item/42") type = "application/json" putExtra("user_id", "123") } val request = DeepLinkRequest( intent = intent, extras = requestExtras { put(CampaignIdExtrasKey, "spring_promo") } ) // The resulting DeepLinkRequest contains: val uri = request.uri // "https://www.example.com/item/42" val action = request.extras[DeepLinkRequest.ActionExtrasKey] // "android.intent.action.VIEW" val mimeType = request.extras[DeepLinkRequest.Companion.MimeTypeExtrasKey] // "application/json" val intentExtras: SavedState? = request.extras[DeepLinkRequest.IntentExtrasKey] val userId: String? = intentExtras?.read { getStringOrNull("user_id") } // "123" val campaignId: String? = request.extras[CampaignIdExtrasKey] // "spring_promo"
DeepLinkMatcher 인스턴스 만들기
DeepLinkMatcher는 수신 DeepLinkRequest 인스턴스를
앱의 백 스택에 추가할 수 있는 탐색 키에 매핑합니다. Navigation 3
은 세 가지 기본 제공 일치자를 제공합니다. 패턴 기반 URI 일치를 위한 UriDeepLinkMatcher, 기본 링크를 위한 StaticKeyDeepLinkMatcher, 합성 백 스택 빌드를 위한
BackStackMatcher입니다. 라이브러리는 기본 제공
일치자로 처리되지 않는 사용 사례를 위한 맞춤 일치자도 지원합니다.
자세한 내용은 DeepLinkMatchers 만들기를 참고하세요.
인텐트 필터 추가하기
딥 링크를 사용하여 활동을 시작하려면 앱의 AndroidManifest.xml에서 일치하는
<intent-filter> 요소를 정의해야 합니다. 자세한 내용은
수신 링크의 인텐트 필터 추가하기를 참고하세요.
수신 요청 일치
`DeepLinkMatcher` 인스턴스를 만든DeepLinkMatcher 후 활동에서 수신 요청을 일치시킬 수 있습니다.
수신 요청을 일치시키려면 다음 단계를 완료하세요.
DeepLinkMatcher인스턴스를 인스턴스화 합니다.- 명시적으로 또는
멀티바인딩을 사용하여 모든
DeepLinkMatcher인스턴스를**대조** 합니다. - 수신
Intent에서DeepLinkRequest를 만듭니다. - 모든 일치자에 대해 요청을 일치 시키고 가장 적합한 일치자를 찾습니다.
- 일치 결과에서 백 스택을 만듭니다.
// 1. Instantiate your DeepLinkMatcher instances. val homeMatcher = StaticKeyDeepLinkMatcher(HomeKey, listOf(DeepLinkMatcher.actionFilter(Intent.ACTION_VIEW))) val userProfileMatcher = UriDeepLinkMatcher( DeepLinkUri("www.example.com/users/{id}"), serializer<UserProfileKey>() ).withBackStack { matchResult -> listOf(HomeKey, matchResult.key) } val telMatcher = TelDeepLinkMatcher() // 2. Collate all of your DeepLinkMatcher instances. // Note: Collating matchers with different generic types requires wildcards, // erasing the specific generic types. val deepLinkMatchers: List<DeepLinkMatcher<*, *>> = listOf( homeMatcher, userProfileMatcher, telMatcher ) class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... // 3. Create a DeepLinkRequest from the incoming Intent val request = DeepLinkRequest(intent = intent) // 4. Match the request against all matchers and find the best match. // Because DeepLinkMatcher.MatchResult implements Comparable, you can // use maxOrNull() to find the best match. val matchResult = deepLinkMatchers .mapNotNull { it.match(request) } // List<DeepLinkMatcher.MatchResult<*>> .maxOrNull() // DeepLinkMatcher.MatchResult<*>? // 5. Create the back stack from the match result (or fall back to a default). val backStack: List<NavKey> = when (matchResult) { // If no match is found, use the default back stack (e.g., HomeKey) null -> listOf(HomeKey) // If a BackStackMatchResult is found, use the back stack from the result is BackStackMatchResult<*, *> -> { // Because star-projected matchers erase the key type, cast the back stack to List<NavKey>. @Suppress("UNCHECKED_CAST") matchResult.backStack as List<NavKey> } // Otherwise, use the key from the match result to make a single-item back stack else -> listOf(matchResult.key as NavKey) } } }