Skip to content

Instantly share code, notes, and snippets.

@aashreys
Last active November 20, 2019 06:00
Show Gist options
  • Save aashreys/fd8a14e652b7c80b784dc90be235d208 to your computer and use it in GitHub Desktop.
Save aashreys/fd8a14e652b7c80b784dc90be235d208 to your computer and use it in GitHub Desktop.
Simple helper to check if Chrome Tabs is supported on a device and open urls.
public class ChromeTabUtils {
public static void openUrl(Context context, String url) {
if (isChromeTabSupported(context)) {
// Build intent to open Chrome Tab
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setToolbarColor(getColor(context, R.color.toolbarBackground));
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(context, Uri.parse(url));
} else {
// Build intent to open any browser
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(browserIntent);
}
}
private static boolean isChromeTabSupported(Context context) {
// Get default VIEW intent handler that can view a web url.
Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.test-url.com"));
// Get all apps that can handle VIEW intents.
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolvedActivityList = pm.queryIntentActivities(activityIntent, 0);
for (ResolveInfo info : resolvedActivityList) {
Intent serviceIntent = new Intent();
serviceIntent.setAction(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION);
serviceIntent.setPackage(info.activityInfo.packageName);
if (pm.resolveService(serviceIntent, 0) != null) {
return true;
}
}
return false;
}
}
@alextcn
Copy link

alextcn commented May 24, 2018

Clean solution. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment