这是一个简单的Kotlin天气服务库,提供了获取全球城市天气信息的API接口。该库支持通过城市名称或地理坐标查询当前天气状况。
将库添加到你的项目中:
// build.gradle.kts
repositories {
mavenLocal() // 添加本地Maven仓库
mavenCentral()
}
dependencies {
implementation("com.example:weather-api:1.0.0")
}
// build.gradle repositories { mavenLocal() // 添加本地Maven仓库 mavenCentral() } dependencies { implementation 'com.example:weather-api:1.0.0' }
<dependency>
<groupId>com.example</groupId>
<artifactId>weather-api</artifactId>
<version>1.0.0</version>
</dependency>
import com.example.weatherapi.WeatherServiceFactory
import kotlinx.coroutines.runBlocking
fun main() {
// 获取模拟的天气服务
val weatherService = WeatherServiceFactory.createMockWeatherService()
// 或者使用真实的WeatherStack API (需要注册获取API密钥)
// val weatherService = WeatherServiceFactory.createWeatherStackService("YOUR_API_KEY")
runBlocking {
// 通过城市名称查询
val weatherResult = weatherService.getCurrentWeather("beijing")
weatherResult.onSuccess { weatherData ->
println("城市: ${weatherData.location.name}")
println("温度: ${weatherData.current.temperature}°C")
println("天气: ${weatherData.current.weather_descriptions.joinToString()}")
}.onFailure { error ->
println("查询失败: ${error.message}")
}
// 通过坐标查询
val coordinatesResult = weatherService.getCurrentWeatherByCoordinates(51.5074, -0.1278)
coordinatesResult.onSuccess { weatherData ->
println("查询到的城市: ${weatherData.location.name}")
}
}
}
./gradlew :modules:weather-api:build
./gradlew :modules:weather-api:test
要将库发布到本地Maven仓库,请执行以下命令:
./gradlew :modules:weather-api:publishToMavenLocal
发布后,该库将可在本地Maven仓库中使用(通常位于~/.m2/repository/com/example/weather-api/1.0.0/)。
在完成发布后,你可以修改应用程序的构建文件,从直接依赖项目改为使用Maven仓库中的库:
// 从这个
implementation(project(":modules:weather-api"))
// 改为这个
implementation("com.example:weather-api:1.0.0")
modules/weather-api/ ├── src/ │ ├── main/ │ │ └── kotlin/ │ │ └── com/ │ │ └── example/ │ │ └── weatherapi/ │ │ ├── WeatherService.kt // 服务接口 │ │ ├── WeatherServiceFactory.kt // 工厂类 │ │ ├── impl/ │ │ │ ├── MockWeatherService.kt // 模拟实现 │ │ │ └── WeatherStackService.kt // 真实API实现 │ │ └── model/ │ │ └── WeatherData.kt // 数据模型 │ └── test/ │ └── kotlin/ │ └── com/ │ └── example/ │ └── weatherapi/ │ └── MockWeatherServiceTest.kt // 测试类 └── build.gradle.kts // 构建配置