共计 3426 个字符,预计需要花费 9 分钟才能阅读完成。
背景痛点
在安卓端集成 ChatGPT API 时,开发者通常会遇到几个典型问题:

- 网络延迟问题 :ChatGPT 的响应时间较长,尤其是在移动网络环境下,可能导致 UI 卡顿
- 大响应解析 :API 返回的 JSON 数据可能包含大量文本,传统解析方式容易出现性能瓶颈
- 线程安全问题 :网络请求需要在后台线程执行,而 UI 更新必须在主线程,线程管理不当容易引发崩溃
- 错误处理复杂 :API 可能返回各种错误状态,需要完善的异常处理机制
技术选型
对于网络库的选择,我们对比了三种主流方案:
- Retrofit:
- 优势:类型安全、支持协程、注解式 API 定义
-
适合场景:结构化 API 调用、需要强类型支持
-
Volley:
- 优势:自动缓存、请求优先级
-
适合场景:小型应用、简单请求场景
-
OkHttp:
- 优势:底层控制力强、拦截器机制
- 适合场景:需要深度定制网络行为的场景
基于 ChatGPT API 的特点,我们选择 Retrofit + Kotlin Coroutine 的组合,因为它能完美解决线程安全和异步问题,同时保持代码简洁。
核心实现
1. 使用 Kotlin Coroutine 实现异步调用
协程是处理异步操作的理想选择。我们可以这样定义 API 接口:
interface ChatGptApi {@POST("v1/chat/completions")
suspend fun getCompletion(@Body request: ChatRequest): Response<ChatResponse>
}
2. 结合 Gson 处理 JSON 响应
定义请求和响应模型时,使用 @SerializedName 注解确保字段映射正确:
data class ChatRequest(@SerializedName("model") val model: String,
@SerializedName("messages") val messages: List<Message>
)
data class Message(@SerializedName("role") val role: String,
@SerializedName("content") val content: String
)
3. 通过 LiveData 实现 UI 数据绑定
在 ViewModel 中暴露 LiveData 给 UI 层:
class ChatViewModel : ViewModel() {private val _response = MutableLiveData<String>()
val response: LiveData<String> = _response
fun sendMessage(message: String) {
viewModelScope.launch {
try {val result = repository.getCompletion(message)
_response.value = result.choices.first().message.content} catch (e: Exception) {// 错误处理}
}
}
}
完整代码示例
下面是一个完整的 ChatGPT 服务封装类:
class ChatGptService(private val api: ChatGptApi) {
/**
* 获取聊天回复
* @param prompt 用户输入
* @param model 使用的模型,默认 gpt-3.5-turbo
*/
suspend fun getChatResponse(
prompt: String,
model: String = "gpt-3.5-turbo"
): Result<String> {
return try {
val request = ChatRequest(
model = model,
messages = listOf(Message(role = "user", content = prompt)
)
)
val response = api.getCompletion(request)
if (response.isSuccessful) {response.body()?.let { body ->
Result.success(body.choices.first().message.content)
} ?: Result.failure(Exception("Empty response body"))
} else {Result.failure(Exception("API error: ${response.code()}"))
}
} catch (e: Exception) {Result.failure(e)
}
}
}
性能优化
1. 响应缓存策略
实现简单的内存缓存:
class ChatCache {private val cache = mutableMapOf<String, String>()
fun get(key: String): String? = cache[key]
fun put(key: String, value: String) {if (cache.size > MAX_CACHE_SIZE) {cache.clear()
}
cache[key] = value
}
companion object {const val MAX_CACHE_SIZE = 100}
}
2. 内存泄漏预防
- 使用
viewModelScope管理协程生命周期 - 避免在 Activity/Fragment 中直接持有网络相关的引用
3. 网络状态处理
监听网络状态变化:
class NetworkMonitor(context: Context) {private val connectivityManager = context.getSystemService<ConnectivityManager>()
val isConnected: Boolean
get() = connectivityManager?.activeNetworkInfo?.isConnected ?: false}
生产环境避坑指南
1. API Key 安全存储方案
使用 Android Keystore 保护 API Key:
fun encryptApiKey(context: Context, apiKey: String): ByteArray {val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateSecretKey())
return cipher.doFinal(apiKey.toByteArray())
}
2. 速率限制处理
实现简单的请求队列和重试机制:
class RateLimiter(private val maxRequests: Int, private val timeWindow: Long) {private val requestTimestamps = ArrayDeque<Long>()
suspend fun acquire() {while (true) {synchronized(this) {val now = System.currentTimeMillis()
// 移除过期的请求记录
while (requestTimestamps.isNotEmpty() &&
now - requestTimestamps.first > timeWindow) {requestTimestamps.removeFirst()
}
if (requestTimestamps.size < maxRequests) {requestTimestamps.addLast(now)
return
}
}
delay(100) // 等待一段时间后重试
}
}
}
3. 长文本分块处理
对于超长响应,可以分段处理:
fun processLongText(text: String, chunkSize: Int = 2000): List<String> {return text.chunked(chunkSize)
}
延伸思考
本文介绍了基础的 ChatGPT API 集成方案,你还可以尝试以下进阶功能:
- 流式响应 :使用 Server-Sent Events (SSE) 实现实时逐字显示
- 本地模型混合调用 :在设备性能允许的情况下,结合小型本地语言模型
- 对话上下文管理 :维护多轮对话历史,实现更连贯的聊天体验
通过以上优化,你的 ChatGPT 安卓应用将更加稳定、高效,为用户提供更好的体验。
正文完
发表至: 未分类
近两天内
