Linkt輕量級 Kotlin 庫
Linkt 是一個輕量級和簡單的 Kotlin 庫,用于 Android 上的 DeepLink 處理。
設(shè)置
配置根目錄build.gradle:
allprojects { repositories { ... maven { url 'https://jitpack.io' } } }
將Linkt添加到項目build.gradle:
dependencies { implementation 'com.github.jeziellago:Linkt:TAG' }
- 創(chuàng)建
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) } } } }
在多模塊項目中,你應(yīng)該有一個或多個 DeepLinkModule。
- 將你的模塊注冊到
Application#onCreate, 中DeepLinkLoader#setup:
class MyApplication : Application () { override fun onCreate () { super .onCreate() DeepLinkLoader .setup( MyDeepLinkModule ()) } }
- 創(chuàng)建
DeepLinkActivity,并調(diào)用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 獲取數(shù)據(jù)
路徑參數(shù)
- 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")
查詢參數(shù)
- 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")
路徑+查詢參數(shù)
- 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")
評論
圖片
表情
