使用自訂分頁低階 API

建議您使用 AndroidX 瀏覽器程式庫,將應用程式與自訂分頁整合,但您也可以在不使用支援程式庫的情況下啟動自訂分頁。本指南將概略說明如何達成這項目標。

您可以在 [GitHub][1] 上查看支援資料庫的完整實作內容,並做為起點。此外,由於 Chromium 存放區中的檔案無法直接與 Android Studio 搭配使用,因此這個檔案也包含連線至服務所需的 [AIDL 檔案][2]。

使用低階 API 啟動自訂分頁的基本概念

// Using a VIEW intent for compatibility with any other browsers on device.
// Caller should not be setting FLAG_ACTIVITY_NEW_TASK or 
// FLAG_ACTIVITY_NEW_DOCUMENT. 
String url = ¨https://paul.kinlan.me/¨;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 
//  Must have. Extra used to match the session. Its value is an IBinder passed
//  whilst creating a news session. See newSession() below. Even if the service is not 
//  used and there is no valid session id to be provided, this extra has to be present 
//  with a null value to launch a custom tab.

private static final String EXTRA_CUSTOM_TABS_SESSION = "android.support.customtabs.extra.SESSION";
Bundle extras = new Bundle;
extras.putBinder(EXTRA_CUSTOM_TABS_SESSION, 
   sessionICustomTabsCallback.asBinder() /* Set to null for no session */);
intent.putExtras(extras);

新增 UI 自訂項目

如要加入 UI 自訂項目,請將 Extras 新增至 ACTION_VIEW 意圖。如需用於自訂 UI 的額外鍵完整清單,請參閱 [CustomTabsIntent 文件][3]。以下範例說明如何新增自訂工具列顏色:

// Extra that changes the background color for the address bar. colorInt is an int
// that specifies a Color.

private static final String EXTRA_CUSTOM_TABS_TOOLBAR_COLOR = "android.support.customtabs.extra.TOOLBAR_COLOR";
intent.putExtra(EXTRA_CUSTOM_TABS_TOOLBAR_COLOR, colorInt);

連線至 Custom Tabs 服務

自訂分頁服務的使用方式與其他 Android 服務相同。介面是使用 AIDL 建立,並會自動為您建立 Proxy 服務類別。

使用 Proxy 服務的方法來暖身、建立工作階段及預先擷取:

// Package name for the Chrome channel the client wants to connect to. This
// depends on the channel name.
// Stable = com.android.chrome
// Beta = com.chrome.beta
// Dev = com.chrome.dev
public static final String CUSTOM_TAB_PACKAGE_NAME = "com.chrome.dev";  // Change when in stable

// Action to add to the service intent. This action can be used as a way 
// generically pick apps that handle custom tabs for both activity and service 
// side implementations.
public static final String ACTION_CUSTOM_TABS_CONNECTION =
       "android.support.customtabs.action.CustomTabsService";
Intent serviceIntent = new Intent(ACTION_CUSTOM_TABS_CONNECTION);

serviceIntent.setPackage(CUSTOM_TAB_PACKAGE_NAME);
context.bindService(serviceIntent, mServiceConnection,
                    Context.BIND_AUTO_CREATE | Context.BIND_WAIVE_PRIORITY);    

[1]:https://github.com/GoogleChrome/custom-tabs-client/tree/master/customtabs [2]:https://developer.android.com/guide/components/aidl.html [3]:https://developer.android.com/reference/androidx/browser/customtabs/CustomTabsIntent