phicdy devlog

Androidアプリ開発やその他技術系の記事をたまに書きます

AndroidとかiOSとかモバイル多め。その他技術的なことも書いていきます。

Chrome Custom TabでデフォルトブラウザがChrome以外の場合の対応

デフォルトブラウザがChrome以外のとき、FirefoxChrome Custom Tabで開いてくれるがドルフィンブラウザなどは非対応のブラウザではそちらが開いてしまう。

f:id:phicdy:20190714185147g:plain

Chrome Custom TabのIntentに com.android.chrome を指定してあげればChrome Custom Tabで開けるようになる。万が一Chromeがないまたは無効化されている場合に備えて ActivityNotFoundException をハンドリングしておく。 今回はSnackbarを指定しているが、もっと丁寧にやるならWebViewで開くようにしてあげるともっといいかもしれない。

try {
    val customTabsIntent = CustomTabsIntent.Builder()
            .setShowTitle(true)
            .setToolbarColor(ContextCompat.getColor(activity, R.color.background_toolbar))
            .build()
    customTabsIntent.intent.setPackage("com.android.chrome") // Chromeを指定
    customTabsIntent.launchUrl(context, Uri.parse(url))
} catch (e: ActivityNotFoundException) {
    // Chromeがない、または無効にされている
    Snackbar.make(findViewById(R.id.fab), R.string.open_internal_browser_error, Snackbar.LENGTH_SHORT).show()
}