Od wersji 1.2.0 komponent Navigation 3 obsługuje precyzyjne linki do miejsc docelowych w aplikacji za pomocą klas DeepLinkRequest i DeepLinkMatcher.
Aby obsługiwać precyzyjne linki w aplikacji, wykonaj te czynności:
- Zdefiniuj filtry intencji w pliku
AndroidManifest.xml, aby określić, które identyfikatory URI może obsługiwać Twoja aplikacja. - Utwórz instancje
DeepLinkMatcher, aby mapować przychodzące żądania na klucze nawigacyjne. - Dopasuj przychodzące żądania w metodzie
onCreatelubonNewIntentaktywności i odpowiednio zaktualizuj stos wsteczny.
Utwórz DeepLinkRequest
DeepLinkRequest reprezentuje przychodzący precyzyjny link. Zawiera on element DeepLinkUri i opcjonalny element RequestExtras z dodatkowymi informacjami, takimi jak działanie intencji lub typ MIME.
// 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") } )
Dodaj DeepLinkRequest dodatkowych komponentów
Aby przechowywać dodatkowe informacje związane z precyzyjnym linkiem, użyj klasy RequestExtras. Aby zapewnić bezpieczeństwo typów podczas definiowania i tworzenia instancji dodatków, biblioteka udostępnia interfejs RequestExtrasKey i język DSL requestExtras.
Dodatkowo biblioteka udostępnia 2 klucze dodatków i powiązane z nimi funkcje pomocnicze:
MimeTypeExtrasKey: służy do przechowywania typu MIMEString.ActionExtrasKey(tylko na Androidzie): służy do przechowywania działaniaIntentString.
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)
Aby zdefiniować własne niestandardowe parametry dodatkowe, zaimplementuj interfejs RequestExtrasKey z wpisanym typem ogólnym:
// Define a custom typed key: object CampaignIdExtrasKey : RequestExtrasKey<String> val customExtras: RequestExtras = requestExtras { put(CampaignIdExtrasKey, "123") } val campaignId: String? = customExtras[CampaignIdExtrasKey]
Możesz też użyć emptyRequestExtras(), aby utworzyć pustą instancję, lub połączyć dodatki za pomocą operatorów + (plus) i - (minus).
Tworzenie DeepLinkRequest z Intent
Na urządzeniu z Androidem możesz utworzyć DeepLinkRequest bezpośrednio z Intent. W takim przypadku DeepLinkRequest jest tworzony w ten sposób:
- Wartość
urijest kopiowana z poladataintencji. - Jeśli nie jest pusta, typ MIME i dodatki działania są ustawiane na podstawie odpowiednich pól intencji.
- Wszystkie
intent.extrasz wartościami innymi niż null są zapisywane jakoSavedStatewDeepLinkRequest.IntentExtrasKey. - Dodawane są wszystkie dodatkowe parametry podane za pomocą parametru
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"
Utwórz instancje DeepLinkMatcher
DeepLinkMatcher mapuje przychodzące instancje DeepLinkRequest na klawisze nawigacyjne, które można dodać do stosu wstecznego aplikacji. Nawigacja 3 udostępnia 3 wbudowane dopasowania: UriDeepLinkMatcher do dopasowywania identyfikatorów URI na podstawie wzorców, StaticKeyDeepLinkMatcher do podstawowych linków i BackStackMatcher do tworzenia syntetycznych stosów wstecznych. Biblioteka obsługuje też niestandardowe dopasowania w przypadkach, które nie są obsługiwane przez wbudowane dopasowania.
Więcej informacji znajdziesz w artykule Tworzenie obiektów DeepLinkMatcher.
Dodawanie filtrów intencji
Aby umożliwić precyzyjnemu linkowi rozpoczęcie aktywności, musisz zdefiniować pasujące elementy <intent-filter> w pliku AndroidManifest.xml aplikacji. Więcej informacji znajdziesz w artykule Dodawanie filtrów intencji do linków przychodzących.
Dopasowywanie żądania przychodzącego
Po utworzeniu instancji DeepLinkMatcher możesz dopasowywać przychodzące żądania w swojej aktywności.
Aby dopasować przychodzące żądanie, wykonaj te czynności:
- Utwórz instancje
DeepLinkMatcher. - Zbierz wszystkie instancje
DeepLinkMatcher, bezpośrednio lub za pomocą wielowiązań. - Utwórz
DeepLinkRequestz przychodzącegoIntent. - Dopasuj żądanie do wszystkich dopasowań i znajdź najlepsze dopasowanie.
- Utwórz stos wsteczny na podstawie wyniku dopasowania.
// 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) } } }