Deeplink定義
deeplink是用于設置一個web鏈接,將鏈接嵌入到web頁面中,當用戶點擊外部鏈接時由瀏覽器對鏈接進行解析并打開自己的項目APP,并跳轉(zhuǎn)到APP內(nèi)特定界面。
Deeplink設置
配置文件配置
配置AndroidManifest.xml文件,在Activity中設置<intent-filter>,并填充必要的屬性,示例代碼如下:
<activity
android:name=".DeepLinkActivity"
android:noHistory="true">
<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:host="@string/deeplink_host"
android:scheme="@string/deeplink_scheme"/>
</intent-filter>
</activity>
- 聲明action為action.VIEW確保能夠應用能夠接受到deeplink請求。
- deeplink樣式和URL樣式相同,如示例代碼中的deeplink就是scheme://host。
- 如果包含有多個deeplink,則可以聲明多個intent-filter,變更啟動的data配置即可。
代碼中判斷和實現(xiàn)deeplink
- 我們可以將項目內(nèi)的deeplink封裝在獨立的Activity中,deeplink的判斷愛Activity中完成。
- 通過對URI的解析確定deeplink對應的地址應該執(zhí)行的操作,如:
var data = intent.data
if (data?.host != null) {
when (data.host) {
getString(R.string.deeplink_host) -> {
toTargetPage()
}
else -> {
finish()
}
}
} else
finish()
通過intent 獲取到對應的URI并進行host,path等具體的解析完成特定的跳轉(zhuǎn)。
Deeplink adb測試
為了能夠更加快速方便的測試deeplink是否起到了對應的效果,我們可以采用adb指令的方式來快速訪問deeplink。
adb指令
adb指令的格式為
adb shell am start -W -a android.intent.action.VIEW -d "具體的deeplink地址" packageName
示例如下:
adb shell am start -W -a android.intent.action.VIEW -d "scheme://host" com.example.deeplinkdemo
Uri結構和Deeplink進一步應用
uri的詳細結構如下:
[scheme:][//host:port][path][?query][#fragment]
Deeplink主要是通過具體的Uri跳轉(zhuǎn)到APP內(nèi)部特定的頁面,因此其核心內(nèi)容是URI結構內(nèi)容,可以通過URI結構設置特定的參數(shù),然后通過這些特定的參數(shù)達到能夠傳遞特殊參數(shù)的效果或者目的,此處便不再展示。
備注
本篇內(nèi)容只是展示的最簡單的deeplink開發(fā)和使用,URI方面更是采用了最簡單的格式進行說明。
GitHub demo地址