建议使用 AndroidX Browser 库将应用与自定义标签页集成,但您也可以在不使用支持库的情况下启动自定义标签页。本指南简要介绍了如何实现此目标。
支持库的完整实现可在 [GitHub][1] 上找到,并可用作起点。它还包含连接到服务所需的 [AIDL 文件][2],因为 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.
val url = "https://paul.kinlan.me/"
val intent = 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.
val extraCustomTabsSession = "android.support.customtabs.extra.SESSION"
val extras = Bundle()
extras.putBinder(
extraCustomTabsSession,
sessionICustomTabsCallback.asBinder() /* Set to null for no session */
)
intent.putExtras(extras)
添加界面自定义
通过向 ACTION_VIEW intent 添加 extra 来实现界面自定义。如需查看用于自定义界面的 extra 键的完整列表,请参阅 [CustomTabsIntent 文档][3]。以下示例展示了如何添加自定义工具栏颜色:
// Extra that changes the background color for the address bar. colorInt is an int
// that specifies a Color.
val extraCustomTabsToolbarColor = "android.support.customtabs.extra.TOOLBAR_COLOR"
intent.putExtra(extraCustomTabsToolbarColor, colorInt)
连接到 Custom Tabs 服务
自定义标签页服务的使用方式与其他 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
val customTabPackageName = "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.
val actionCustomTabsConnection =
"android.support.customtabs.action.CustomTabsService"
val serviceIntent = Intent(actionCustomTabsConnection)
serviceIntent.setPackage(customTabPackageName)
// serviceConnection is your ServiceConnection implementation. Its
// onServiceConnected() callback receives the IBinder for the Custom Tabs service.
context.bindService(
serviceIntent,
serviceConnection,
Context.BIND_AUTO_CREATE or 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