【Android】Android / Kotlin でYoutube/Browserを起動する

■ はじめに

https://dk521123.hatenablog.com/entry/2020/07/20/232009

の続き。

Android で 英単語帳を作っているのだが
単語を覚えるための補助として、
関連したURLからYoutube/Browserを起動する

■ サンプル

MainActivity.kt

// ...

        // 呼び出し部分
        val targetUrl = "https://www.youtube.com/watch?v=vq-xgxJ3_gQ"
        this.launchByUrl(targetUrl)
    }

    private fun launchByUrl(targetUrl: String) {
        val url = Url(targetUrl)
        if (!url.isUrl()) {
            return
        } else if (url.isYouTube()) {
            this.launchYoutube(url)
        } else {
            this.launchBrowser(targetUrl)
        }
    }

    private fun launchBrowser(url: String) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
        this.startActivity(intent)
    }

    private fun launchYoutube(targetUrl: Url) {
        try {
            val intent = Intent(
                Intent.ACTION_VIEW,
                Uri.parse("vnd.youtube:" + targetUrl.getVideoId()))
            this.startActivity(intent)
        } catch (ex: Exception) {
            // error
            Log.w(ex.message, ex)

            // Retry
            this.launchBrowser(targetUrl.url)
        }
    }

Url.kt

class Url(url: String) {
    val url: String = url
    var protocol: String? = null
    var host: String? = null
    var port: String? = null
    var other: String? = null

    init {
        val regex = Regex("""^(.+?)://(.+?):?(\d+)?(/.*)?${'$'}""")
        val match = regex.find(url)
        this.protocol = match?.groupValues?.get(1)
        this.host = match?.groupValues?.get(2)
        this.port = match?.groupValues?.get(3)
        this.other = match?.groupValues?.get(4)
    }

    fun isUrl(): Boolean {
        return this.protocol == "https" || this.protocol == "http"
    }

    fun isYouTube(): Boolean {
        return this.isUrl() &&
                this.host?.endsWith("youtube.com", true)!!
    }

    fun getVideoId(): String? {
        if (!this.isYouTube() || this.other == null) {
            return null
        }
        val regex = Regex("""/watch\?v=([\w-]{11})""")
        val match = regex.find(this.other!!)
        return match?.groupValues?.get(1)
    }
}

参考文献

https://blog.ch3cooh.jp/entry/20160913/1473726600

関連記事

Kotlin / Realm で英単語帳を作る
https://dk521123.hatenablog.com/entry/2020/07/20/232009
Kotlin ~ 基本編 / 正規表現
https://dk521123.hatenablog.com/entry/2020/10/16/000000