Debug模式正常但Release模式出现ParameterizedType错误的修复方法
问题描述
应用基于Firebase Auth实现登录功能,支持Google OAuth和邮箱登录。Debug构建下登录流程正常,但Release构建中出现以下错误:
024-10-16 15:34:52.847 18432-18432 AuthViewModel com.logomo.logomo E Error fetching API key: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType package com.logomo.logomo.data.login.
已确认是ProGuard混淆导致的问题,将isMinifyEnabled设为false后功能恢复正常。
核心代码片段
ViewModel登录逻辑
private suspend fun loginAndGetApiKey(uid: String) { try { _isLoading.value = true logInResponse = logInRepository.signInUser(uid) // Suspends here until API call finishes logInResponse?.let { _apiKey.value = it.api_key Log.d(TAG, "getApiKey: ${it.status}") Log.d(TAG, "getApiKey: ${apiKey.value}") // Save the API key and retrieve it safely apiKey.value?.let { it1 -> saveApiKey(apiKey = it1) } val savedApiKey = getApiKey() Log.d(TAG, "getApiKeyFunc: $savedApiKey") } ?: run { Log.e(TAG, "Login response is null, failed to retrieve API key") } } catch (e: Exception) { signOut() Log.e(TAG, "Error fetching API key: ${e.message}") } finally { _isLoading.value = false } }
ApiService接口
import com.logomo.logomo.retrofit.SignInUserData import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST interface LogInApiService { @FormUrlEncoded @POST("users/user_login.php") suspend fun signInUser( @Field("uid") uid: String, ): SignInUserData }
Repository类
import com.logomo.logomo.retrofit.SignInUserData import javax.inject.Singleton @Singleton class NetworkLogInRepository( private val logInApiService: LogInApiService ) { suspend fun signInUser(uid: String): SignInUserData { return logInApiService.signInUser(uid) } }
解决方案
该错误是ProGuard混淆破坏了Retrofit依赖的反射机制(尤其是数据模型类的类型信息)导致的,需在proguard-rules.pro中添加以下规则:
- 保护Retrofit核心组件
# Retrofit2 核心规则 -dontwarn retrofit2.** -keep class retrofit2.** { *; } -keepattributes Signature -keepattributes Exceptions
- 保护API接口和数据模型类(关键)
# 保留登录相关API接口 -keep interface com.logomo.logomo.data.login.LogInApiService { *; } # 保留SignInUserData数据类的所有字段和方法,避免反射解析失败 -keep class com.logomo.logomo.retrofit.SignInUserData { <fields>; <methods>; } # 如果有其他Retrofit数据模型,统一保留可替换为: # -keep class com.logomo.logomo.retrofit.** { *; }
- 保护依赖注入与协程相关类
若使用Hilt/Dagger,需保留注入相关类:
# Hilt/Dagger 依赖注入规则 -keep class com.logomo.logomo.data.login.NetworkLogInRepository { *; } -keep @javax.inject.Singleton class *
- 保护EncryptedSharedPreferences组件
-keep class androidx.security.crypto.** { *; } -dontwarn androidx.security.crypto.**
额外验证步骤
- 确保
build.gradle中Release构建配置正确引用规则文件:
buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } }
- 执行
Clean Project后重新构建Release版本,避免缓存干扰。
内容的提问来源于stack exchange,提问作者Shivanshu Raj
相关产品推荐
相关产品推荐

