Step 1: Add Custom Tabs Dependency
First, add the Chrome Custom Tabs library to your build.gradle file:
dependencies {
implementation 'androidx.browser:browser:1.5.0' // Check for the latest version
}
Add this in your activity or Fragment :
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import androidx.browser.customtabs.CustomTabsService
import androidx.browser.customtabs.CustomTabsServiceConnection
import androidx.browser.customtabs.CustomTabsSession
fun openCustomTab(context: Context, url: String) {
val customTabsIntent = CustomTabsIntent.Builder().apply {
setToolbarColor(context.getColor(R.color.your_toolbar_color)) // Set the custom toolbar color
addDefaultShareMenuItem() // Adds a share button to the toolbar
setShowTitle(true) // Show the page title in the toolbar
}.build()
// Check if Chrome is available and supports Custom Tabs
val packageName = getChromePackageName(context)
if (packageName != null) {
customTabsIntent.intent.setPackage(packageName)
customTabsIntent.launchUrl(context, Uri.parse(url))
} else {
// Fallback: Open in a browser if Chrome is not available
openInBrowserFallback(context, url)
}
}
private fun getChromePackageName(context: Context): String? {
val packageManager = context.packageManager
val customTabsPackages = packageManager.queryIntentServices(
Intent(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION), 0
)
for (info in customTabsPackages) {
if (info.serviceInfo.packageName.equals("com.android.chrome", true)) {
return info.serviceInfo.packageName
}
}
return null
}
private fun openInBrowserFallback(context: Context, url: String) {
try {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
context.startActivity(browserIntent)
} catch (e: ActivityNotFoundException) {
// Handle the error (e.g., show a message to the user)
e.printStackTrace()
}
}
Customizations:
Replace R.color.your_toolbar_color with the actual color resource you want to use for the toolbar.
You can add more UI customizations as needed by modifying the CustomTabsIntent.Builder.