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:scheme | scheme | 必填。協議頭,如 `http`、`https`、或自定義 `myapp`。建議用包名倒序避免衝突。 |
android:host | host | 域名/主機名,如 `www.example.com` 或 `detail`。無 scheme 時被忽略。 |
android:port | port | 端口號。無 host 時被忽略。 |
android:pathandroid:pathPrefixandroid:pathPattern | path | 路徑匹配:精確 / 前綴 / 正則。無 host 時被忽略。 |
自定義鏈接: 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") 獲取
@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/頁面
}
}