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

Android 產品研發:應用內跳轉 Scheme 協議實踐

編輯:關於 Android 程式設計

本文講解一種 App 內頁面跳轉協議,涵蓋應用內跳轉、H5 與 Native 互跳、服務器通知客戶端跳轉等場景。

在深入之前,先談談 H5 與 Native 的相互跳轉。如今越來越多 App 採用 Native + H5 混合開發,兩者如何交互?Google 提供了一種通用方式:JS 與 Native 互調——JS 能調 Native 方法,Native 也能調 JS 方法。

但這種方式存在不少問題:

1、Java 調 JS 函數效率不高(約 200ms),而 JS 調 Java 方法很快(約 50ms),因此盡量用 JS 去調 Java。

2、Java 調 JS 函數沒有返回值,調用完便失控。

3、JS 調 Java 若返回字符串,會發現它是 native 格式,需轉成 locale 才能正常使用(可用 toLocaleString(),但該函數速度不快,字符串多時頗耗時)。

4、網頁中盡量別用 jQuery,執行要 5-6 秒,最好用原生 JS 寫業務腳本以提升加載速度。

5、Android 4.2 以下存在 WebView 的 JS 對象注入漏洞。

基於以上種種原因,我們並未採用互調方式,而是採用 scheme + cookie 的方案。這裡的 scheme 是一種頁面內跳轉協議,主要支持三種場景:

服務器下發跳轉路徑,客戶端據此跳轉相應頁面;H5 頁面點擊錨點,按錨點路徑跳轉 App 頁面;App 收到服務器下發的 PUSH 通知,按點擊路徑跳轉相關頁面。

URL Scheme 概述

URL Scheme 的作用

客戶端應用可向操作系統注冊一個 URL scheme,用於從瀏覽器或其他應用啟動本應用。通過指定的 URL 字段,能在應用被調起後直接打開特定頁面(如車輛詳情、訂單詳情、消息通知、促銷廣告等),也可執行指定動作(如訂單支付),甚至能在應用內通過 HTML 頁面直接調起某個原生頁面。

URL Scheme 的格式

客戶端自定義 URL 作為應用間相互調用的基礎,遵循 RFC 1808 標准,與常見網頁 URL 格式一致。一個普通 URL 分為 scheme、host、relativePath、query 幾部分。

例如 https://www.baidu.com/s?rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709 中,scheme 為 http,host 為 www.baidu.com,relativePath 為 /s,query 為其餘參數。

再看一個應用內的例子 uumobile://mobile/carDetail?car_id=123456:scheme 為 uumobile,host 為 mobile,relativePath 為 /carDetail,query 為 car_id=123456,它會調起車輛詳情頁。

用 Scheme 定義 Activity

1)在 AndroidManifest.xml 中定義 scheme。要想被其他 App 成功調起,必須添加 intent-filter:

<intent-filter>
    <data android:scheme="uumobile" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
</intent-filter>

如此便定義了一個能接受 scheme 請求的 Activity,當網頁或代碼發送符合規則的 scheme 請求時,就能吊起這個 Native 頁面。

2)實現 NativeAppActivity,在其中解析 scheme 並執行相應動作:

public class NativeAppActivity extends Activity {
    public void onCreate(Bundle b) {
        super.onCreate(b);
        Uri uri = getIntent().getData();
        if (uri != null) {
            List<String> pathSegments = uri.getPathSegments();
            if (pathSegments != null && pathSegments.size() > 0) {
                // 解析 SCHEME
                if (someCondition) {
                    doSomething();
                } else {
                    finish(); // 解析不到則關閉
                }
            } else {
                finish();
            }
        } else {
            finish();
        }
    }
}

比如請求跳轉登錄頁,可定義為 uumobile://appname/gotoLogin,解析出該結構後便跳轉登錄頁。可通過 Intent 對象獲取調用信息:

this.getIntent().getScheme();      // 獲得 Scheme 名稱
this.getIntent().getDataString();  // 獲得 Uri 全部路徑

3)服務器下發跳轉路徑:

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("uumobile://yongche/123123123")));

執行 startActivity 時便會調起 NativeAppActivity,再由它解析 scheme 內容、跳轉相應頁面。

4)H5 頁面錨點跳轉:為 WebView 設置 WebViewClient 並重寫 shouldOverrideUrlLoading,解析錨點 URL 後調起 scheme Activity:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.indexOf(H5Constant.SCHEME) != -1) {
        try {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            h5Activity.startActivityForResult(intent, H5Constant.h5RequestCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    } else if (url.indexOf("tel:") != -1) {
        // 打電話
        final String number = url.substring("tel:".length());
        Config.callPhoneByNumber(h5Activity, number);
        return true;
    } else {
        view.loadUrl(url);
        return false;
    }
}

可見我們解析錨點 URL,據其內容調起 Native 的 scheme Activity,再在其中解析並跳轉目標頁面。

5)根據服務器下發的通知欄消息跳轉:所有通知都先跳轉到 NotificationActivity,在其中判斷通知是否在有效期內,據此選擇不同的 action URL 並構建 Intent 跳轉,同時做點擊統計。核心的 buildSchemeFromUrl 方法負責從 url 中解析出 Intent 對象:

public static Intent buildSchemeFromUrl(String url) {
    if (url != null && url.indexOf(H5Constant.SCHEME) != -1) {
        Uri uri = Uri.parse(url);
        String[] urlSplit = url.split("\\?");
        Map<String, String> queryMap = new HashMap<>();
        String h5Url = null;
        if (urlSplit.length == 2) {
            queryMap = H5Constant.parseUriQuery(urlSplit[1]);
            h5Url = queryMap.get(H5Constant.MURL);
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        if (!TextUtils.isEmpty(h5Url)) {
            intent.putExtra(H5Constant.MURL, h5Url);
        }
        return intent;
    }
    return null;
}

這樣便構造出跳轉 Native 頁面的 Intent,並把 scheme 字符串傳遞過去,由目標頁解析並執行相應邏輯。

總結:Android 的 scheme 是一種非常便利的機制。通過定義自有的 scheme 協議,可以輕松跳轉 App 內各個頁面;服務器也能藉此定制化地告知 App 該跳去哪裡——無論是通過通知欄消息,還是 H5 頁面。


本文已同步至 GitHub:https://github.com/yipianfengye/androidProject,歡迎 star 和 follow。


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