Linkt轻量级 Kotlin 库

联合创作 · 2023-09-25 02:28

Linkt 是一个轻量级和简单的 Kotlin 库,用于 Android 上的 DeepLink 处理。


设置


配置根目录build.gradle




allprojects { repositories { ... maven { url 'https://jitpack.io' } } }


Linkt添加到项目build.gradle




dependencies { implementation 'com.github.jeziellago:Linkt:TAG' }



  1. 创建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。




  1. 将你的模块注册到Application#onCreate, 中DeepLinkLoader#setup




class MyApplication : Application () { override fun onCreate () { super .onCreate() DeepLinkLoader .setup( MyDeepLinkModule ()) } }



  1. 创建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")


 

浏览 24
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报