首先,需要在 AndroidManifest.xml 裡的 Activity 區段宣告以下:
<activity ...>
<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="myApp" />
<data android:host="profilePage" />
</intent-filter>
</activity>
一個 URI 是由以下所組成:<scheme>://<host>:<port>[<path>|<pathPrefix>|<pathPattern>]
所以程式 A 就可以透過 URI myApp://profilePage 把程式 B 給叫起來:
// Application A start application B via the intent with URI.
Intent i = new Intent();
i.setData(Uri.parse("myApp://profilePage"));
// Check whether the intent can be resolved.
if (i.resolveActivity(getPackageManager()) != null) {
startActivity(i);
}
甚至 URI 後面也可以帶 query:
myApp://profilePage?uid=12&uname=Sean
再透過 Uri 的方法 getQueryParameterNames 和 getQueryParameter 來取得 key 和 value。
測試的方法
測試的方法有三種:- 直接寫程式碼執行。
- 用 Android Studio 來執行
Run -> Edit Configuration... -> Launch Options -> URL
在 URL 的欄位輸入 URI 然後執行。
用這個方法的缺點是只能測 action=android.intent.action.VIEW 而且 category=android.intent.category.BROWSER 的 activity。 - 透過 adb command line (推薦的方法)
輸入 adb 指令:
adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSER -d myApp://profilePage
Ref:
- <data>
https://developer.android.com/guide/topics/manifest/data-element.html - Support HTTP URLs in Your App
https://firebase.google.com/docs/app-indexing/android/app?hl=zh-tw#reference-the-noindexxml-file - Testing URLs with Android Studio
https://firebase.google.com/docs/app-indexing/android/test#lint-checks-for-links
沒有留言:
張貼留言