To open a browser in Android using an Intent, you can use the ACTION_VIEW intent and provide a URL. Here’s how you can do it.
Example Code in Jetpack Compose
MainActivity.kt
package com.example.openbrowserexample
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            OpenBrowserScreen()
        }
    }
    @Composable
    fun OpenBrowserScreen() {
        Scaffold(
            topBar = { TopAppBar(title = { Text("Open Browser Example") }) }
        ) { padding ->
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
                    .padding(16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Button(onClick = {
                    openBrowser("https://www.google.com")
                }) {
                    Text("Open Google")
                }
                Spacer(modifier = Modifier.height(20.dp))
                Button(onClick = {
                    openBrowser("https://developer.android.com")
                }) {
                    Text("Open Android Developer Docs")
                }
            }
        }
    }
    private fun openBrowser(url: String) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
        startActivity(intent)
    }
}Explanation
- Button to Open URL:
- The Buttontriggers theopenBrowser()function, passing the URL to be opened.
- Intent with ACTION_VIEW:
- The Intentis created withIntent.ACTION_VIEWand aUri.parse(url)to specify the URL.
- Start Browser Activity:
- The startActivity(intent)method launches the browser with the specified URL.
Features
- Opens the default web browser installed on the device.
- Allows easy switching between different URLs.
Permissions
- No special permissions are needed to open the browser.
Notes
If you’d like to handle the result from the browser or verify if the browser is available before launching the Intent, let me know!