Last active
November 20, 2019 06:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Clean solution. Thank you!