android studio用Kotlin获取天气代码
时间: 2023-06-25 15:02:20 浏览: 81
以下是使用 Kotlin 在 Android Studio 中获取天气代码的示例:
首先,在你的 `build.gradle` 文件中添加以下依赖项:
```groovy
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation("com.squareup.moshi:moshi-kotlin:1.12.0")
implementation("com.squareup.moshi:moshi-adapters:1.12.0")
implementation("com.squareup.moshi:moshi-kotlin-codegen:1.12.0")
```
接下来,在你的 Activity 或 Fragment 中创建一个函数来获取天气数据:
```kotlin
private fun fetchWeatherData() {
val url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY&units=metric"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// 处理失败情况
}
override fun onResponse(call: Call, response: Response) {
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val jsonAdapter = moshi.adapter(WeatherResponse::class.java)
val weatherResponse = jsonAdapter.fromJson(response.body?.string())
// 在 UI 线程中更新 UI
runOnUiThread {
// 更新 UI
}
}
})
}
```
注意替换 URL 中的 `YOUR_API_KEY` 为你的 OpenWeatherMap API 密钥。
最后,定义一个数据类来解析 JSON 响应:
```kotlin
data class WeatherResponse(
val name: String,
val main: Main,
val weather: List<Weather>
)
data class Main(
val temp: Double,
val humidity: Int
)
data class Weather(
val main: String,
val description: String
)
```
这些代码将使用 OkHttp 库发送 HTTP 请求,并使用 Moshi 库解析 JSON 响应。当响应成功返回时,将在 UI 线程中更新 UI。