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

混合開發核心:H5 頁面與 Native App 的交互方案

編輯:關於 Android 程式設計

混合開發(Hybrid App)的做法是在 App 中嵌入一個輕量級瀏覽器,把一部分原生功能改用 H5 實現。這樣做的好處很明顯:頁面可以不升級 App 就動態更新,同一套代碼還能同時跑在 Android 和 iOS 上,既提升了用戶體驗,又節省了研發成本。

而混合開發繞不開的核心話題就是:H5 和 Native 之間怎麼互相調用。比如點了 H5 上的按鈕能不能跳轉到某個原生頁面,點了分享按鈕能不能調起原生的分享面板,H5 加載時能不能拿到原生的登錄用戶信息。

主流方案有兩類:

1. JS 調用 Native 中的代碼;
2. Scheme:由 WebView 攔截頁面跳轉。

第二種實現起來非常簡單,但有個致命短板——它是單向的,H5 無法拿到回調。一旦需求變複雜,例如 H5 需要讀取 Native 的用戶信息,就必須改用 JS 調用方案。典型場景是從淘寶客戶端進入天貓 H5 頁面購物,這時 H5 必須能獲取已登錄用戶的狀態。

一、方案一:JS 與 Native 雙向交互

關鍵只有兩步:讓 WebView 支持 JS,再把對象暴露給 JS。

WebSettings webSettings = mWebview.getSettings();
webSettings.setJavaScriptEnabled(true);                                  // ① 允許調用 js
webSettings.setDefaultTextEncodingName("UTF-8");
mWebview.addJavascriptInterface(new MyObject(TestWebViewActivity.this), "myObj");  // ② 暴露對象

被暴露的 Java 對象,方法上加 @JavascriptInterface 註解即可被 JS 調用:

public class MyObject {
    private Context context;

    public MyObject(Context context) {
        this.context = context;
    }

    /** 暴露給 JS:彈 Toast */
    @JavascriptInterface
    public void showToast(String name) {
        Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
    }

    /** 暴露給 JS:彈自定義對話框 */
    @JavascriptInterface
    public void showDialog() {
        new AlertDialog.Builder(context)
                .setTitle("聯系人列表")
                .setIcon(R.mipmap.ic_launcher)
                .setItems(new String[]{"基神", "B神", "曹神", "街神", "翔神"}, null)
                .setPositiveButton("確定", null)
                .create()
                .show();
    }
}

H5 側只需一行:myObj.showToast("hello")。注意 Android 4.2 起必須加註解,這既是調用要求,也是對早期反射注入漏洞的修補。

二、方案二:Scheme 攔截頁面跳轉

思路是約定一個自定義協議,WebView 在 shouldOverrideUrlLoading 中判斷 scheme,命中就交給系統去解析,由 Intent 完成頁面跳轉。

public class TestWebViewActivity extends BaseActivity {
    @InjectView(R.id.webview) WebView mWebview;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        super.mLoadingDialog.hideLoading();
        mWebview.loadUrl("file:///android_asset/test.html");

        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse(url);
                if (uri.getScheme().equals("xl")) {
                    // 自定義協議,交給系統解析
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                } else {
                    view.loadUrl(url);
                }
                return true;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebview != null) {
            mWebview.destroy();     // 記得銷燬,避免內存洩漏
        }
    }
}

靜態頁面中只需一個鏈接:

<a href="xl://goods/goodsDetail">test scheme</a>

目標頁面要在 Manifest 中配置 intent-filter,否則無法被外部調起:

<intent-filter>
    <!-- 協議部分,可自定義 -->
    <data
        android:host="goods"
        android:path="/goodsDetail"
        android:port="8888"
        android:scheme="xl" />

    <!-- 下面兩行必須設置 -->
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
</intent-filter>

適用場景:定義自己的 scheme 協議後,可以非常便捷地在 App 各頁面之間跳轉;服務端也能通過推送、通知欄消息、H5 頁面等途徑定制化成跳指令,直接告訴 App 該去哪個頁面,覆蓋面已經相當廣。

三、開源項目的做法:路由表 + 正則匹配

大型項目通常不會散落地寫 scheme 判斷,而是集中一張「URL → Activity」的路由表。以 coding 的實現為例,核心就是拿一組正則去匹配傳入的 URI,命中後裝好參數再跳轉:

public static boolean openActivityByUri(Context context, String uri, boolean newTask,
                                        boolean defaultIntent, boolean share) {
    Intent intent = new Intent();
    if (newTask) {
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    final String NAME = "([\\w.-]+)";
    final String uriString = uri.replace("/team/", "/user/").replace("/t/", "/u/");
    final String uriPath = uriString.replace(Global.HOST, "");

    // 例:/u/{user}/p/{project}/topic/{id}
    final String topic = "^(?:https://[\\w.]*)?/u/([\\w.-]+)/p/([\\w.-]+)/topic/([\\w.-]+)(?:\\?[\\w=&-]*)?$";
    Pattern pattern = Pattern.compile(topic);
    Matcher matcher = pattern.matcher(uriString);
    if (matcher.find()) {
        intent.setClass(context, TopicListDetailActivity_.class);
        TopicListDetailActivity.TopicDetailParam param =
                new TopicListDetailActivity.TopicDetailParam(
                        matcher.group(1), matcher.group(2), matcher.group(3));
        intent.putExtra("mJumpParam", param);
        context.startActivity(intent);
        return true;
    }

    // 例:/u/{user}/p/{project}  → 項目首頁
    final String project = "^(?:https://[\\w.]*)?/u/([\\w.-]+)/p/([\\w.-]+)(/git)?$";
    pattern = Pattern.compile(project);
    matcher = pattern.matcher(uriString);
    if (matcher.find()) {
        intent.setClass(context, ProjectHomeActivity_.class);
        intent.putExtra("mJumpParam", new ProjectActivity.ProjectJumpParam(
                matcher.group(1), matcher.group(2)));
        context.startActivity(intent);
        return true;
    }

    // ……其餘分支:git 文件、merge/pull、commit、branch、附件預覽、圖片鏈接等

    // 兜底:交給 WebActivity 打開原始鏈接
    if (defaultIntent) {
        intent = new Intent(context, WebActivity_.class);
        intent.putExtra("url", uri.startsWith("/u/") ? Global.HOST + uri : uri);
        if (share) intent.putExtra("share", true);
        context.startActivity(intent);
    }
    return false;
}

本質上這是和服務端約定了一套 URL 規範,用正則把 URL 解析成結構化參數,再分發到對應頁面。代碼看起來繁瑣,但作用與 scheme 類似,而且統一入口便於維護、埋點與兜底。

四、兩種方案如何選

- 只需要「H5 → Native」單向跳轉:用 Scheme,成本最低;
- 需要 Native 把數據回傳給 H5,或 H5 要讀取設備與賬戶信息:用 addJavascriptInterface;
- 大型項目建議兩者結合,並引入統一路由層,避免判斷邏輯散落在各個 WebView 頁面裡。
- 無論哪種方案,都要記得銷燬 WebView,並對 JS 接口做域名白名單校驗,防止被惡意頁面調用。

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