NetworkInfo弃用

优快云博客解析
'val activeNetworkInfo: NetworkInfo?' is deprecated. Deprecated in Java.'val isConnected: Boolean' is deprecated. Deprecated in Java.This is a delicate API and its use requires care. Make sure you fully read and understand documentation of the declaration that is marked as a delicate API.package com.example.aaosweatherapp import android.content.Context import android.net.ConnectivityManager import okhttp3.OkHttpClient import okhttp3.Request import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.ByteArrayInputStream import java.io.IOException import java.util.zip.GZIPInputStream class WeatherApiManager(private val context: Context) { // 替换为你的 API 凭证(从和风天气控制台获取) private val API_HOST = "pg5egkugvt.re.qweatherapi.com" // 你的专属 API Host private val API_KEY = "62362dfbc9e140c5b7e8d2ab92e17678" // 你的 API Key(二选一) private val client = OkHttpClient() private val gson = Gson() // 城市 ID 映射(可扩展更多城市) private val cityIdMap = mapOf( "101010100" to "北京", "101020100" to "上海", "101280101" to "广州", "101280601" to "深圳", "101030100" to "天津", "101190101" to "南京", "101210101" to "杭州", "101230101" to "厦门", ) // 异步获取天气数据(二选一认证方式,注释掉另一种) fun fetchWeather(cityId: String, onSuccess: (WeatherData) -> Unit, onFailure: (String) -> Unit) { // 1. 检查网络连接 val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val isConnected = connectivityManager.activeNetworkInfo?.isConnected == true if (!isConnected) { onFailure("无网络连接,请检查网络") return } // 2. 构建 API 请求 URL(按官方格式) val url = "https://$API_HOST/v7/weather/now?location=$cityId" // 3. 构建请求(配置标头,启用 Gzip 解压) val requestBuilder = Request.Builder() .url(url) .addHeader("Accept-Encoding", "gzip") // 告知服务器支持 Gzip // 认证方式二选一:API Key(推荐) .addHeader("X-QW-Api-Key", API_KEY) // 认证方式二选一:JWT(注释上面一行,启用下面一行) // .addHeader("Authorization", "Bearer $JWT") GlobalScope.launch(Dispatchers.IO) { try { // 4. 发送请求并获取响应 val response = client.newCall(requestBuilder.build()).execute() if (!response.isSuccessful) { withContext(Dispatchers.Main) { onFailure("请求失败:状态码 ${response.code}") } return@launch } // 5. 解压 Gzip 响应数据(核心步骤) val responseBody = response.body?.byteStream() ?: throw IOException("无响应数据") val jieyaData = decompressGzip(responseBody.readBytes()) val responseStr = jieyaData.toString(Charsets.UTF_8) // 6. 解析 JSON 数据 val apiResponse = gson.fromJson(responseStr, WeatherApiResponse::class.java) if (apiResponse.code != "200") { withContext(Dispatchers.Main) { onFailure("API 错误:${apiResponse.code}(请检查城市ID和凭证)") } return@launch } // 7. 转换为展示用数据模型(新增图标字段赋值) val nowData = apiResponse.now val weatherCondition = nowData.text // 获取天气状况(如"晴") val weatherIconRes = WeatherIconMapper.getIconRes(weatherCondition) // 匹配图标 val weatherData = WeatherData( city = cityIdMap[cityId] ?: "未知城市", temperature = "${nowData.temp}℃", condition = weatherCondition, wind = "${nowData.windScale}级${nowData.windDir}", humidity = "${nowData.humidity}%", feelsLike = "${nowData.feelsLike}℃", iconRes = weatherIconRes // 赋值图标资源ID ) // 8. 回调成功结果(主线程更新 UI) withContext(Dispatchers.Main) { onSuccess(weatherData) } } catch (e: Exception) { withContext(Dispatchers.Main) { onFailure("异常:${e.message ?: "未知错误"}") } } } } // Gzip 解压工具方法 private fun decompressGzip(compressedData: ByteArray): ByteArray { return GZIPInputStream(ByteArrayInputStream(compressedData)).use { inputStream -> inputStream.readBytes() } } }
最新发布
11-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值