2

I have simple button in android jetpack compose, when I click the button, I want to open gmail and send mail to "android@gmail.com", is it possible?

@Composable
    fun SimpleButton() {
        Button(onClick = {
            //your onclick code here
        }) {
            Text(text = "Simple Button")
        }
    }
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Huma33
  • 59
  • 7

1 Answers1

8

You have to create an Intent and then start an Activity with it, similar to how you would have to do it normally.

The only difference in Compose is that you obtain the Context with LocalContext.current.

@Composable
fun SimpleButton() {
    val context = LocalContext.current
    Column {
        Button(onClick = {
            context.sendMail(to = "example@gmail.com", subject = "Some subject")
        }) {
            Text(text = "Send mail")
        }

        Button(onClick = {
            context.dial(phone = "12345678")
        }) {
            Text(text = "Dial number")
        }
    }
}

fun Context.sendMail(to: String, subject: String) {
    try {
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "vnd.android.cursor.item/email" // or "message/rfc822"
        intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(to))
        intent.putExtra(Intent.EXTRA_SUBJECT, subject)
        startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        // TODO: Handle case where no email app is available
    } catch (t: Throwable) {
        // TODO: Handle potential other type of exceptions
    }
}

fun Context.dial(phone: String) {
    try {
        val intent = Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null))
        startActivity(intent)
    } catch (t: Throwable) {
        // TODO: Handle potential exceptions
    }
}

For more possibilities see answers here, but keep in mind that some are outdated.

Ma3x
  • 5,761
  • 2
  • 17
  • 22