Hum*_*a33 2 android kotlin android-jetpack android-jetpack-compose
我在 android jetpack compose 中有一个简单的按钮,当我单击该按钮时,我想打开 gmail 并将邮件发送到“android@gmail.com”,这可能吗?
@Composable
fun SimpleButton() {
Button(onClick = {
//your onclick code here
}) {
Text(text = "Simple Button")
}
}
Run Code Online (Sandbox Code Playgroud)
您必须创建一个 Intent,然后用它启动一个 Activity,这与您通常的做法类似。
Compose 中的唯一区别是您获得了Contextwith 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
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多可能性,请参阅此处的答案,但请记住,有些答案已经过时了。