Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

讓其他 App 輕鬆喚起你的 Activity:Scheme 跳轉完全指南

編輯:關於 Android 程式設計

開發一款能被更多使用者使用的 App,往往意味著我們需要對外提供一組標準的呼叫介面,讓第三方應用能夠直接喚起我們的功能。像大眾點評、豆瓣這類內容豐富的應用,就是靠著開放的 Scheme 打通了彼此之間的資源流通。

以豆瓣為例,它在 AndroidManifest 中這樣宣告了一個可對外響應的 Activity:

<activity android:name="com.douban.movie.PlayVideoActivity">
    <intent-filter>
        <action android:name="com.douban.movie" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="http"
              android:host="movie.douban.com"
              android:pathPattern="/trailer/.*/" />
    </intent-filter>
</activity>

關鍵在於兩個宣告

這段設定裡最要緊的兩處,一是加入了 android.intent.category.BROWSABLE,讓瀏覽器或網頁連結都能觸發;二是透過 <data> 標籤定義了 scheme、host 與 pathPattern:

<data android:scheme="http"
      android:host="movie.douban.com"
      android:pathPattern="/trailer/.*/" />

把 Scheme 寫成類似 URL 的形式,最大的好處是應用內跳轉與網頁跳轉可以共用同一套邏輯,維護起來相當方便。

處理「對方沒安裝 App」的情況

現實中我們無法保證使用者的手機一定裝了目標 App。若第三方應用硬是以 Scheme 跳轉,而對方並未安裝,就會出錯誤。常見的解法是用 try-catch 包起來,一旦失敗就退回網頁版本。以大眾點評為例,它選擇把 App Scheme 與網址分開處理:

String id = "3102397";
try {
    Uri url = Uri.parse("dianping://shopinfo?id=" + id);
    Intent intent = new Intent(Intent.ACTION_VIEW, url);
    mContext.startActivity(intent);
} catch (Exception e) {
    // 沒有安裝應用,預設打開 HTML5 站
    Intent intent = new Intent(Intent.ACTION_VIEW,
            Uri.parse("https://m.dianping.com/shop/" + id));
    mContext.startActivity(intent);
}

透過這種「先試 App、失敗再導向網頁」的策略,無論使用者是否安裝了對應應用,都能獲得流暢且不至于中斷的體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved