使用 Custom Tab 低级别 API

推荐使用 AndroidX 浏览器库将应用与自定义标签页集成,但您也可以在不使用支持库的情况下启动自定义标签页。本指南将简要介绍如何实现此目标。

GitHub 上提供了支持库的完整实现,可用作 起点它还包含连接到该服务所需的 AIDL 文件, 无法直接用于 Android Studio。

使用 Low Level 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);

添加界面自定义

向 ACTION_VIEW intent 添加 Extra 即可纳入界面自定义。所有 您可以在 CustomTabsIntent 文档中找到用于自定义界面的 extras 键。以 如何添加自定义工具栏颜色:

// 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);

连接到自定义标签页服务

自定义标签页服务的使用方式与其他 Android 服务相同。界面是 并使用 AIDL 自动创建代理服务类。

使用代理服务上的方法预热、创建会话和预提取:

// 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);