How can I open a URL in Android's web browser from my application?

前端 未结 30 2722
庸人自扰
庸人自扰 2020-11-21 22:09

How to open an URL from code in the built-in web browser rather than within my application?

I tried this:

try {
    Intent myIntent = new Intent(Int         


        
30条回答
  •  迷失自我
    2020-11-21 22:54

    The Kotlin answer:

    val browserIntent = Intent(Intent.ACTION_VIEW, uri)
    ContextCompat.startActivity(context, browserIntent, null)
    

    I have added an extension on Uri to make this even easier

    myUri.openInBrowser(context)
    
    fun Uri?.openInBrowser(context: Context) {
        this ?: return // Do nothing if uri is null
    
        val browserIntent = Intent(Intent.ACTION_VIEW, this)
        ContextCompat.startActivity(context, browserIntent, null)
    }
    

    As a bonus, here is a simple extension function to safely convert a String to Uri.

    "https://stackoverflow.com".asUri()?.openInBrowser(context)
    
    fun String?.asUri(): Uri? {
        try {
            return Uri.parse(this)
        } catch (e: Exception) {}
        return null
    }
    

提交回复
热议问题