Android 通过Chrome Custom Tab打开网页
在日常开发中,偶尔会需要在App中打开网页,通常会使用WebView来实现。本文介绍一下另一种实现方式Chrome Custom Tab。
Chrome Custom Tab
Custom Tab是Chrome浏览器引入的一个功能,现在市面上大部分安卓设备的浏览器都已经支持此功能。Custom Tab使App原生内容与网页内容的过渡更加流畅,支持自定义部分样式,可以保持与App一致的风格,支持预加载。
添加库
在app module下的build.gradle中添加代码,如下:
dependencies {
implementation 'androidx.browser:browser:1.5.0'
}
检查Custom Tab是否可用
尽管现在市面上大部分安卓设备的浏览器都已支持Custom Tab,但为了确保部分设备不支持该功能的情况下用户体验正常,可以先检查当前设备是否支持该功能,不支持的话仍然通过WebView实现。代码如下:
fun checkCustomTabAvailable(context: Context): Boolean {
val packageManager = context.packageManager
val browsableIntent = Intent().apply {
action = Intent.ACTION_VIEW
addCategory(Intent.CATEGORY_BROWSABLE)
data = Uri.fromParts("http", "", null)
}
// 获取所有浏览器
val browsableResolverInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.queryIntentActivities(browsableIntent, PackageManager.ResolveInfoFlags.of(0))
} else {
packageManager.queryIntentActivities(browsableIntent, 0)
}
val supportingCustomTabResolveInfo = ArrayList<ResolveInfo>()
browsableResolverInfo.forEach {
val serviceIntent = Intent().apply {
action = androidx.browser.customtabs.CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION
setPackage(it.activityInfo.packageName)
}
val customTabServiceResolverInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.resolveService(serviceIntent, PackageManager.ResolveInfoFlags.of(0))
} else {
packageManager.resolveService(serviceIntent, 0)
}
// 判断是否可以处理Custom Tabs service
if (customTabServiceResolverInfo != null) {
supportingCustomTabResolveInfo.add(it)
}
}
return supportingCustomTabResolveInfo.isNotEmpty()
}
打开网页
通过Custom Tab打开网页代码如下:
fun openCustomTab(context: Context, url: String) {
// url 为要打开的网址
CustomTabsIntent.Builder().build().launchUrl(context, url.toUri())
}
需要注意的是,不能通过此方式打开Assets下的H5文件。
调整UI
Custom Tab支持自定义部分样式。
调整视图高度
可以使用CustomTabsIntent.Builder
中的setInitialActivityHeightPx
方法来调整打开的Custom Tab的高度,同时可以使用setToolbarCornerRadiusDp
来设置圆角。具体实现方式有如下两种:
-
- 连接Custom Tab Service(建议使用此方式)。
``` // 辅助类 object CustomTabHelper {
// Custom Tab 可用的包名
private var customTabAvailablePackageName: String = ""
private var customTabsClient: CustomTabsClient? = null
private var customTabsServiceConnection: CustomTabsServiceConnection? = null
fun openCustomTabWithInitialHeight(context: Context, url: String, activityHeight: Int = 0, radius: Int = 0, adjustable: Boolean = false) {
val customTabsIntentBuilder = CustomTabsIntent.Builder(customTabsClient?.newSession(null))
if (activityHeight != 0) {
// 第二个参数配置预期行为
// ACTIVITY_HEIGHT_ADJUSTABLE 用户可以手动调整视图高度
// ACTIVITY_HEIGHT_FIXED 用户无法手动调整视图高度
customTabsIntentBuilder.setInitialActivityHeightPx(activityHeight, if (adjustable) CustomTabsIntent.ACTIVITY_HEIGHT_ADJUSTABLE else CustomTabsIntent.ACTIVITY_HEIGHT_FIXED)
if (radius != 0) {
customTabsIntentBuilder.setToolbarCornerRadiusDp(radius)
}
}
customTabsIntentBuilder.build().launchUrl(context, url.toUri())
}
fun checkCustomTabAvailable(context: Context): Boolean {
val packageManager = context.packageManager
val browsableIntent = Intent().apply {
action = Intent.ACTION_VIEW
addCategory(Intent.CATEGORY_BROWSABLE)
data = Uri.fromParts("http", "", null)
}
// 获取所有浏览器
val browsableResolverInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.queryIntentActivities(browsableIntent, PackageManager.ResolveInfoFlags.of(0))
} else {
packageManager.queryIntentActivities(browsableIntent, 0)
}
val supportingCustomTabResolveInfo = ArrayList<ResolveInfo>()
browsableResolverInfo.forEach {
val serviceIntent = Intent().apply {
action = androidx.browser.customtabs.CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION
setPackage(it.activityInfo.packageName)
}
val customTabServiceResolverInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.resolveService(serviceIntent, PackageManager.ResolveInfoFlags.of(0))
} else {
packageManager.resolveService(serviceIntent, 0)
}
// 判断是否可以处理Custom Tabs service
if (customTabServiceResolverInfo != null) {
supportingCustomTabResolveInfo.add(it)
}
}
if (supportingCustomTabResolveInfo.isNotEmpty()) {
customTabAvailablePackageName = supportingCustomTabResolveInfo[0].activityInfo.packageName
}
return supportingCustomTabResolveInfo.isNotEmpty()
}
fun bindCustomTabsService(activity: Activity) {
if (checkCustomTabAvailable(activity)) {
if (customTabsClient == null) {
customTabsServiceConnection = object : CustomTabsServiceConnection() {
override fun onCustomTabsServiceConnected(name: ComponentName, client: CustomTabsClient) {
customTabsClient = client
}
override fun onServiceDisconnected(name: ComponentName?) {
customTabsClient = null
}
}
customTabsServiceConnection?.let {
CustomTabsClient.bindCustomTabsService(activity, customTabAvailablePackageName, it)
}
}
}
}
fun unbindCustomTabsService(activity: Activity) {
customTabsServiceConnection?.let { activity.unbindService(it) }
customTabsClient = null
customTabsServiceConnection = null
}
}
// 示例Activity class CustomTabExampleActivity : BaseGestureDetectorActivity() {
private val url = "http://go.minigame.vip/"
private var activityHeight = 0
private var topRadius = 16
private var changeHeightAdjustable = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: LayoutCustomTabActivityBinding = DataBindingUtil.setContentView(this, R.layout.layout_custom_tab_activity)
activityHeight = (resources.displayMetrics.heightPixels * 0.8).toInt()
binding.btnChangeHeightFixed.setOnClickListener {
checkCustomTabAvailable()
changeHeightAdjustable = false
CustomTabHelper.openCustomTabWithInitialHeight(this, url, activityHeight, topRadius, changeHeightAdjustable)
}
binding.btnChangeHeightAdjustable.setOnClickListener {
checkCustomTabAvailable()
changeHeightAdjustable = true
CustomTabHelper.openCustomTabWithInitialHeight(this, url, activityHeight, topRadius, changeHeightAdjustable)
}
}
private fun checkCustomTabAvailable() {
if (!CustomTabHelper.checkCustomTabAvailable(this)) {
startActivity(Intent(this, WebViewActivity::class.java).apply { putExtra(PARAMS_LINK_URL, url) })
return
}
}
override fun onStart() {
super.onStart()
CustomTabHelper.bindCustomTabsService(this)
}
override fun onDestroy() {
super.onDestroy()
CustomTabHelper.unbindCustomTabsService(this)
}
} ```
-
- 使用startActivityForResult
``` class CustomTabExampleActivity : BaseGestureDetectorActivity() {
private val url = "http://go.minigame.vip/"
private var activityHeight = 0
private var topRadius = 16
private var changeHeightAdjustable = false
private val customTabLauncher = registerForActivityResult(object : ActivityResultContract<String, Int>() {
override fun createIntent(context: Context, input: String): Intent {
val customTabsIntentBuilder = CustomTabsIntent.Builder()
.setInitialActivityHeightPx(activityHeight, if (changeHeightAdjustable) CustomTabsIntent.ACTIVITY_HEIGHT_ADJUSTABLE else CustomTabsIntent.ACTIVITY_HEIGHT_FIXED)
.setToolbarCornerRadiusDp(topRadius)
return customTabsIntentBuilder.build().intent.apply {
data = input.toUri()
}
}
override fun parseResult(resultCode: Int, intent: Intent?): Int {
return resultCode
}
}) {
// 页面返回回调
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: LayoutCustomTabActivityBinding = DataBindingUtil.setContentView(this, R.layout.layout_custom_tab_activity)
activityHeight = (resources.displayMetrics.heightPixels * 0.8).toInt()
binding.btnChangeHeightFixed.setOnClickListener {
checkCustomTabAvailable()
changeHeightAdjustable = false
customTabLauncher.launch(url)
}
binding.btnChangeHeightAdjustable.setOnClickListener {
checkCustomTabAvailable()
changeHeightAdjustable = true
customTabLauncher.launch(url)
}
}
private fun checkCustomTabAvailable() {
if (!CustomTabHelper.checkCustomTabAvailable(this)) {
startActivity(Intent(this, WebViewActivity::class.java).apply { putExtra(PARAMS_LINK_URL, url) })
return
}
}
} ```
效果如图:
调整地址栏
可以对Custom Tab的地址栏进行一些配置,代码如下:
``` // 辅助类 object CustomTabHelper {
fun openCustomTabWithCustomUI(context: Context, url: String, @ColorInt color: Int = 0, showTitle: Boolean = false, autoHide: Boolean = false, backIconPosition: Int = CustomTabsIntent.CLOSE_BUTTON_POSITION_START) {
val customTabsIntentBuilder = CustomTabsIntent.Builder(customTabsClient?.newSession(null))
if (color != 0) {
// 设置背景颜色
customTabsIntentBuilder.setDefaultColorSchemeParams(CustomTabColorSchemeParams.Builder()
.setToolbarColor(color)
.build())
}
// 是否显示标题
customTabsIntentBuilder.setShowTitle(showTitle)
// 地址栏是否自动隐藏 ,此配置仅在Custom Tab全屏显示时生效
customTabsIntentBuilder.setUrlBarHidingEnabled(autoHide)
// 调整关闭按钮的位置
// CustomTabsIntent.CLOSE_BUTTON_POSITION_START 在地址栏的左侧
// CustomTabsIntent.CLOSE_BUTTON_POSITION_END 在地址栏的右侧
customTabsIntentBuilder.setCloseButtonPosition(backIconPosition)
customTabsIntentBuilder.build().launchUrl(context, url.toUri())
}
}
// 示例Activity class CustomTabExampleActivity : BaseGestureDetectorActivity() {
private val url = "http://go.minigame.vip/"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: LayoutCustomTabActivityBinding = DataBindingUtil.setContentView(this, R.layout.layout_custom_tab_activity)
binding.btnCustomUi.setOnClickListener {
checkCustomTabAvailable()
CustomTabHelper.openCustomTabWithCustomUI(this, url, ContextCompat.getColor(this, R.color.color_FF2600), showTitle = true, autoHide = true, CustomTabsIntent.CLOSE_BUTTON_POSITION_END)
}
}
} ```
效果如图:
调整显示隐藏动画
当Custom Tab为全屏显示时,可以调整显示与隐藏时的动画,代码如下:
```
// slide_in_right
// slide_out_left
// 辅助类 object CustomTabHelper { fun openCustomTabWithCustomAnimations(context: Context, url: String) { val customTabsIntentBuilder = CustomTabsIntent.Builder(customTabsClient?.newSession(null)) // 自定义动画 customTabsIntentBuilder.setStartAnimations(context, R.anim.slide_in_right, R.anim.slide_out_left) // 系统动画 customTabsIntentBuilder.setExitAnimations(context, android.R.anim.slide_in_left, android.R.anim.slide_out_right) customTabsIntentBuilder.build().launchUrl(context, url.toUri()) } }
// 示例Activity class CustomTabExampleActivity : BaseGestureDetectorActivity() {
private val url = "http://go.minigame.vip/"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: LayoutCustomTabActivityBinding = DataBindingUtil.setContentView(this, R.layout.layout_custom_tab_activity)
binding.btnCustomAnimations.setOnClickListener {
checkCustomTabAvailable()
CustomTabHelper.openCustomTabWithCustomAnimations(this, url)
}
}
} ```
效果如图:
示例Demo
在示例Demo中添加了相关的演示代码。
- Android 通过Chrome Custom Tab打开网页
- Android 通过MotionLayot实现点赞动画
- Android FCM接入
- Android 接入Google Tag Manager
- Android 一种点赞动画的实现
- Android 搜索框架使用
- Android WebView JS交互 传Json格式参数问题
- 以往项目中的压缩apk经验
- Android 字体下载
- Android 全屏显示和沉浸式显示
- Android Google支付接入
- Android 自定义Gradle插件(八):检查Manifest中的权限
- Android 自定义View ——渐变色折线图
- Android Activity Result API (二) :拍照与选择照片
- Android 自定义Gradle插件(七):关于多渠道打包
- Android 自定义Gradle插件(六):打包时修改assets中的文件
- Android 自定义Gradle插件(四):在项目的文件夹中创建文件
- 使用Nexus搭建maven私有库
- 记windows下 AndroidStudio 安装配置过程,以及最新版AndroidStuido遇到的一个问题