如何在 Android 處理 App Links?

Android

情境

我是 https://example.com 的擁有者,使用者在我的服務註冊後,我會發送一封 Email 到使用者信箱,附有驗證連結:https://example.com/auth?token=...,我預期:

  1. 手機點擊驗證連結後開啟我的 Android App,顯示「登入完成」頁面。
  2. 電腦點擊驗證連結後用瀏覽器開啟「驗證成功」的網頁。

修改 AndroidManifest.xml

<activity
    android:name="com.example.app.MainActivity"
    android:exported="true">
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" />
        <data android:host="example.com" />
        <data android:pathPrefix="/auth" />
    </intent-filter>
</activity>

首先修改 manifest 裡面的 activity,將 intent-filter 設定加上。

新增 assetlinks.json

在此網址新增檔案:https://example.com/.well-known/assetlinks.json

assetlinks.json 綁定 Android App 的資訊,以下是範例:

[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "target": {
      "namespace": "android_app",
      "package_name": "com.example.app",
      "sha256_cert_fingerprints": [
          "aa:bb:cc:..."
      ]
    }
  }
]

package_namesha256_cert_fingerprints 填上自己的 app 資訊即可。

注意:這個檔案的 Content-Type 要設定為 application/json,不然會出錯。

測試

adb shell am start -W -a android.intent.action.VIEW -d "https://example.com/auth"

透過以上指令可以讓 Android App 處理 https://example.com/auth,如果有喚起 App 就成功了。

adb shell pm get-app-links com.example.app

// 結果
com.example.app:
  ID: a2c50033-96c8-4ce1-a410-fb5c8afa8224
  Signatures: [aa:bb:cc..]
  Domain verification state:
    example.com: verified

以上指令則是可以查看 Android App 跟 assetlinks.json 之間的綁定狀態,綁定成功會顯示:verified

注意事項

  1. assetlinks.jsonContent-Type 要設定為 application/json
  2. 通常 keystore 有分正式環境跟測試環境,兩個 sha256_cert_fingerprints 都要設定。
  3. 我原本的 package name:com.example.app.debug,一直綁定失敗,改成:com.example.app 就成功了,不知原因。

參考資料

Configure, implement, and verify Android App Links

留言列表

標題和URL已復制