Linkt轻量级 Kotlin 库
Linkt 是一个轻量级和简单的 Kotlin 库,用于 Android 上的 DeepLink 处理。
设置
配置根目录build.gradle:
allprojects { repositories { ... maven { url 'https://jitpack.io' } } }
将Linkt添加到项目build.gradle:
dependencies { implementation 'com.github.jeziellago:Linkt:TAG' }
- 创建
DeepLinkModule并注册 deeplinks:
class MyDeepLinkModule : DeepLinkModule {
override fun load() {
deepLinkOf(
"linkt://sample",
"linkt://sample/{userId}/{userName}"
) { context, bundle ->
Intent(context, MainActivity::class.java)
.apply { putExtras(bundle) }
}
}
}
在多模块项目中,你应该有一个或多个 DeepLinkModule。
- 将你的模块注册到
Application#onCreate, 中DeepLinkLoader#setup:
class MyApplication : Application () { override fun onCreate () { super .onCreate() DeepLinkLoader .setup( MyDeepLinkModule ()) } }
- 创建
DeepLinkActivity,并调用DeepLinkLoader#loadFrom:
class DeepLinkActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// resolve deeplink
DeepLinkLoader.loadFrom(this)
}
}
不要忘记配置AndroidManifest.xml:
<activity
android:name="org.linkt.DeepLinkActivity"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="mycompany" />
</intent-filter>
</activity>
如何从 deeplink 获取数据
路径参数
- Template
linkt://sample/{userId}/{userName} - Received:
linkt://sample/9999/Jose
// get path parameters
val userId = intent.extras.getString("userId")
val userId = intent.extras.getString("userName")
查询参数
- Template:
linkt://sample - Received
linkt://sample?subject=Linkt&name=Sample
// get query parameters
val subject = intent.extras.getString("subject")
val name = intent.extras.getString("name")
路径+查询参数
- Template
linkt://sample/{userId}/{userName} - Received
linkt://sample/999/Jose?subject=Linkt&name=Sample
// get path parameters
val userId = intent.extras.getString("userId")
val userId = intent.extras.getString("userName")
// get query parameters
val subject = intent.extras.getString("subject")
val name = intent.extras.getString("name")
评论
