Last active
February 3, 2020 08:44
-
-
Save colinrtwhite/d11e485b273ca778a939ae37d8073aa8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
fun Context.openWebPage(url: String): Boolean { | |
// Format the URI properly. | |
val uri = url.toWebUri() | |
// Try using Chrome Custom Tabs. | |
try { | |
val intent = CustomTabsIntent.Builder() | |
.setToolbarColor(getColorCompat(R.color.primary)) | |
.setShowTitle(true) | |
.build() | |
intent.launchUrl(this, uri) | |
return true | |
} catch (ignored: Exception) {} | |
// Fall back to launching a default web browser intent. | |
try { | |
val intent = Intent(Intent.ACTION_VIEW, uri) | |
if (intent.resolveActivity(packageManager) != null) { | |
startActivity(intent) | |
return true | |
} | |
} catch (ignored: Exception) {} | |
// We were unable to show the web page. | |
return false | |
} | |
fun String.toWebUri(): Uri { | |
return (if (startsWith("http://") || startsWith("https://")) this else "https://$this").toUri() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment