Kotlin Practice #14 Compose 跳轉其他APP

Dogpa Chen
5 min readApr 15, 2023

上一篇完成了簡單的水庫API的串接,大概知道要如何透過Retrofit取得網路的資料。

這一篇則要學習如何在Jetpack Compose 點擊某個選項後,跳轉到其他的APP。主要會跳到 chrome / Line / Google Map / 電話 這四個。

首先先建立一個function,建立intent後加入intent的data後推出。

fun openURL(context: Context, url: String) {

// 建立一個Action view的 Intent
val intent = Intent(Intent.ACTION_VIEW)

// 在intent的data加入要前往的網址
intent.data =
Uri.parse(url)

// 執行該intent
startActivity(context, intent, null)
}

接著建立一個MainView

@Composable
fun MainView(name: String, context:Context) {
Column(
modifier = Modifier.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = {
openURL(context,"https://www.facebook.com")
}) {
Text(text = "跳轉網頁Facebook")
}
Button(onClick = {
openURL(context,"https://line.me/ti/p/@mitsubishielectric")
}) {
Text(text = "Line")
}
Button(onClick = {
val openURL = Intent(Intent.ACTION_VIEW)
openURL.data = Uri.parse("http://maps.google.com/maps?saddr=25.034210948537485,121.56403195296623&daddr=武嶺&directionsmode=driving")
startActivity(context, openURL, null )
}) {
Text(text = "跳轉Map")
}
Button(onClick = {
openURL(context,"tel:0912345678")
}) {
Text(text = "致電0912345678")
}
}
}

接著將MainView加入到MainActivity內

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KP14IntentOtherAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
MainView("Android",this)
}
}
}
}
}

來看一下效果如何

基本上這四個都能夠順利跳轉,基本上side project的需要功能就算理解要怎麼執行了。持續加油!!!

--

--