建议您使用 AndroidX 浏览器库将应用与自定义标签页集成,但您也可以在不使用支持库的情况下启动自定义标签页。本指南将简要介绍如何实现这一点。
GitHub 上提供了支持库的完整实现,您可以以此为起点。它还包含连接到服务所需的 AIDL 文件,因为 Chromium 代码库中包含的文件无法直接用于 Android Studio。
使用低级别 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 添加 Extras,可以实现界面自定义。如需查看用于自定义界面的 extra 键的完整列表,请参阅 CustomTabsIntent 文档。以下示例展示了如何添加自定义工具栏颜色:
// 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);