首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Android Deep Link 實戰:自定義 Scheme 協議啟動 App 完整配置指南

     編輯:Java 綜合教學

Android 深度鏈接:通過自定義協議 (Scheme) 直達 App 內頁

Deep Link 允許用戶點擊網頁鏈接、掃碼、或其他 App 分享鏈接時,直接啟動你的 App 並跳轉到指定頁面。核心是在 `AndroidManifest.xml` 中為目標 `Activity` 配置 `` 與 ``。

核心配置代碼

<activity android:name=".MainActivity">
    <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="com.example.androidtest" />
        <!-- 可選:進一步限制 host、port、path -->
        <!-- <data android:host="detail" android:path="/product/123" /> -->
    </intent-filter>
</activity>

關鍵屬性解析

屬性對應 URL 部分說明
android:schemescheme必填。協議頭,如 `http`、`https`、或自定義 `myapp`。建議用包名倒序避免衝突。
android:hosthost域名/主機名,如 `www.example.com` 或 `detail`。無 scheme 時被忽略。
android:portport端口號。無 host 時被忽略。
android:path
android:pathPrefix
android:pathPattern
path路徑匹配:精確 / 前綴 / 正則。無 host 時被忽略。

URL 結構對應示例

自定義鏈接:  com.example.androidtest://detail/product/123?color=red
拆解:
  scheme:  com.example.androidtest   → android:scheme
  host:    detail                    → android:host
  path:    /product/123              → android:path
  query:   color=red                 → 代碼中 getIntent().getData().getQueryParameter("color") 獲取

Activity 中獲取鏈接數據

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    handleIntent(intent); // 單例模式下需處理 onNewIntent
}

private void handleIntent(Intent intent) {
    Uri data = intent.getData();
    if (data != null) {
        String scheme = data.getScheme(); // "com.example.androidtest"
        String host = data.getHost();     // "detail"
        List pathSegments = data.getPathSegments(); // ["/product", "123"]
        String productId = data.getLastPathSegment(); // "123"
        String color = data.getQueryParameter("color"); // "red"
        // 根據參數導航到對應 Fragment/頁面
    }
}

最佳實踐與避坑

  1. Scheme 命名:使用 `com.company.appname` 格式,全局唯一,避免與其他 App 沖突。
  2. 導出風險:配置 `BROWSABLE` 會導致 Activity 被隱式導出,敏感頁面需在代碼中校驗權限或驗證簽名。
  3. 啟動模式:建議目標 Activity 設置 `android:launchMode="singleTask"` 或在 `onNewIntent` 中處理,避免疊加多個實例。
  4. App Links (驗證鏈接):Android 6.0+ 支持 App Links (HTTP/HTTPS 綁定域名),需配置 `android:autoVerify="true"` 並部署 `assetlinks.json`,體驗更佳 (無彈窗選擇器)。
  5. 測試命令:`adb shell am start -W -a android.intent.action.VIEW -d "com.example.androidtest://detail/product/123" com.example.androidtest`
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved