Kotlin Deeplinking Solutions
Overview
Once the domain has been setup under the Open URL Mapping Editor
within Android Studio, we need to
set up the DeepLinkActivity
class:
DeepLinkActivity.kt
package com.example.app
...
class DeepLinkActivity : ComponentActivity() {
private fun handleIntent(intent: Intent?) {
intent?.let {
if (it.action == Intent.ACTION_VIEW) {
val url = it.data.toString()
fetchClickableLink(url)
}
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
handleIntent(intent)
}
private fun fetchClickableLink(uri: String) {
lifecycleScope.launch {
val resolvedLink = withContext(Dispatchers.IO) {
MIClient.resolveUrl(uri)
}
resolvedLink?.let {
deepLinkToProductPage(it)
}
}
}
}
An example where the resolved url is used to open content within the app:
private fun deepLinkToProductPage(url: String) {
URIPath.getProductFromURI(url.toUri())?.let { productId ->
val productDetailIntent = Intent(
Intent.ACTION_VIEW,
"${DeepLinkPattern.baseDestination}/$productId".toUri(),
this@DeepLinkActivity,
MainActivity::class.java
).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
}
try {
startActivity(productDetailIntent)
} catch (e: Exception) {
Log.e(TAG, "Failed to send deep link pending intent", e)
}
}
}