1、修复小程序问题
This commit is contained in:
Elemt 2026-11-09 18:32:20 +08:00
parent 738fb2fe33
commit 158b71fa5e
15 changed files with 180 additions and 56 deletions

View File

@ -4,10 +4,10 @@
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z">
<DropdownSelection timestamp="2026-11-09T09:16:20.249736600Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=JRBI89BIE6AI5TG6" />
<DeviceId pluginId="PhysicalDevice" identifier="serial=Y5DELZR46DZTCI9D" />
</handle>
</Target>
</DropdownSelection>

View File

@ -51,8 +51,8 @@ android {
applicationId = "com.img.rabbit"
minSdk = 24
targetSdk = 37
versionCode = 2
versionName = "1.0.1"
versionCode = 3
versionName = "1.0.3"
multiDexEnabled = true
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"

View File

@ -13,6 +13,7 @@ import com.github.gzuliyujiang.oaid.DeviceID
import com.github.gzuliyujiang.oaid.IGetter
import com.img.rabbit.config.Constants
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.uni.UniMPImmersiveWindow
import com.img.rabbit.utils.ChannelUtils
import com.tencent.mmkv.MMKV
import com.umeng.analytics.MobclickAgent
@ -33,6 +34,8 @@ class BaseApplication : Application() {
override fun onCreate() {
super.onCreate()
// UniMP Activity 运行在独立进程,窗口适配必须在主进程判断之前注册。
UniMPImmersiveWindow.register(this)
// 只有是主进程时,才执行重量级初始化
if (getProcessName(this) == packageName) {
Log.i(TAG, "进行必要的SDK初始化...")

View File

@ -1,11 +1,13 @@
package com.img.rabbit.bean.response
import com.google.gson.annotations.SerializedName
import com.google.gson.annotations.JsonAdapter
import kotlinx.serialization.Serializable
@Serializable
class ConfigEntity {
@SerializedName("client.banner.home") //首页轮播图
@JsonAdapter(HomeBannerListAdapter::class)
var homeBanners: List<HomeBannerEntity?>? = emptyList()
@SerializedName("client.version.upgrade") //版本更新
var versionEntity: VersionEntity? = null

View File

@ -1,10 +1,12 @@
package com.img.rabbit.bean.response
import com.google.gson.annotations.SerializedName
import kotlinx.serialization.Serializable
/** client.banner.home,与 flaunt-android 的 HomeBannerBean 字段一致。 */
@Serializable
data class HomeBannerEntity(
@SerializedName(value = "img", alternate = ["icon"])
val img: String? = null,
val url: String? = null,
val type: String? = null,

View File

@ -0,0 +1,23 @@
package com.img.rabbit.bean.response
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import java.lang.reflect.Type
/** 后端配置兼容单个 banner 对象和 banner 数组。 */
class HomeBannerListAdapter : JsonDeserializer<List<HomeBannerEntity?>> {
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext,
): List<HomeBannerEntity?> = when {
json.isJsonObject -> listOf(context.deserialize(json, HomeBannerEntity::class.java))
json.isJsonArray -> json.asJsonArray.map { item ->
context.deserialize<HomeBannerEntity?>(item, HomeBannerEntity::class.java)
}
json.isJsonNull -> emptyList()
else -> throw JsonParseException("client.banner.home must be an object or array")
}
}

View File

@ -3,7 +3,7 @@ package com.img.rabbit.config
object Constants {
const val RELEASE_BASE_URL = "https://jitutu.batiao8.com" //release
const val DEBUG_BASE_URL = "https://jitutu.batiao8.com" //debug
const val LOG_REQUEST = "RabbitRequest"
const val LOG_REQUEST = "RequestLog"
const val agreementUrl = "https://jitutu.batiao8.com/static/policy-jietutu/user_android.html" //用户协议
const val privacyUrl = "https://jitutu.batiao8.com/static/policy-jietutu/provacy.html"//隐私政策
@ -16,4 +16,4 @@ object Constants {
const val AESDecrypt = "e4rOtnF8tJjtHO7ecZeJHN1rapED5ImB" //解密
const val Signature = "xn08hYoizXhZ1zHP8DVqfCm2yHxPmhil" //加密字符
}
}

View File

@ -140,15 +140,14 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
bottomBar = {
if (isNavigationBarVisible) {
Column(
modifier = Modifier.navigationBarsPadding()
modifier = Modifier
.background(Color.White)
.navigationBarsPadding()
) {
Box(modifier = Modifier.height(52.dp)) {
NavigationBar(
containerColor = if (selectedTab == TabItem.Mine) {
Color(0xFFF9F9F9)
} else {
Color.White
},
containerColor = Color.White,
tonalElevation = 0.dp,
contentColor = Color.Transparent
) {
tabItems.forEachIndexed { index, item ->
@ -359,4 +358,4 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
}
}
}
}
}

View File

@ -22,10 +22,8 @@ import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
@ -57,7 +55,6 @@ import com.img.rabbit.utils.GlobalEventBus
import com.img.rabbit.viewmodel.GeneralViewModel
import com.img.rabbit.viewmodel.LoginViewModel
import com.img.rabbit.viewmodel.MineViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
@ -75,7 +72,7 @@ fun MineScreen(
val context = LocalContext.current
val scope = rememberCoroutineScope()
//用户数据
var userInfo by remember { mutableStateOf(PreferenceUtil.getUserInfo()) }
val userInfo by loginViewModel.userInfo
// 获取当前路由状态
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
@ -92,15 +89,6 @@ fun MineScreen(
}
}
LaunchedEffect(loginViewModel.userInfoResult.value) {
if(loginViewModel.userInfoResult.value != null){
// 等待200ms,确保用户配置已经刷新
delay(200)
userInfo = PreferenceUtil.getUserInfo()
}
}
Box(
modifier = Modifier
.fillMaxSize()
@ -622,4 +610,4 @@ private fun doLogin(generalViewModel: GeneralViewModel, navController: NavHostCo
@Composable
private fun PreviewMineScreen(){
MineScreen(navController = rememberNavController(), loginViewModel = viewModel(), generalViewModel = viewModel())
}
}

View File

@ -2,6 +2,7 @@
package com.img.rabbit.provider.api
import android.util.Log
import com.batiao.batiaosdk.SignInterceptor
import com.img.rabbit.BuildConfig
import com.img.rabbit.config.Constants
@ -10,6 +11,7 @@ import com.img.rabbit.provider.utils.ResponseInterceptor
import com.img.rabbit.provider.utils.getUnsafeOkHttpClient
import com.img.rabbit.viewmodel.`interface`.ServiceVo
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
@ -39,6 +41,7 @@ object ApiManager {
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(HeaderInterceptor())
.addDebugRequestLogging()
.addInterceptor(SignInterceptor)
.build()
@ -56,6 +59,7 @@ object ApiManager {
.writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(HeaderInterceptor())
.addInterceptor(ResponseInterceptor())
.addDebugRequestLogging()
.addInterceptor(SignInterceptor)
.build()
@ -71,6 +75,19 @@ object ApiManager {
}
}
private fun OkHttpClient.Builder.addDebugRequestLogging(): OkHttpClient.Builder = apply {
if (BuildConfig.DEBUG) {
// 放在签名拦截器外侧,以记录 SDK 解密后的响应。
addInterceptor(HttpLoggingInterceptor { message ->
message.chunked(1000).forEach { chunk ->
Log.d(Constants.LOG_REQUEST, chunk)
}
}.apply {
level = HttpLoggingInterceptor.Level.BODY
})
}
}
// 添加重新初始化方法,用于在baseUrl改变时调用
fun reinitialize() {
// 重置所有实例,使其在下一次访问时重新初始化

View File

@ -132,7 +132,7 @@ object PreferenceUtil {
fun saveUserInfo(userInfoEntity: UserInfoEntity?) {
if(userInfoEntity == null){
mmkv.encode(KEY_USER_INFO, gson.toJson("{}"))
mmkv.remove(KEY_USER_INFO)
}else{
mmkv.encode(KEY_USER_INFO, gson.toJson(userInfoEntity))
}
@ -140,7 +140,8 @@ object PreferenceUtil {
fun getUserInfo(): UserInfoEntity? {
return try {
gson.fromJson(mmkv.decodeString(KEY_USER_INFO, "{}"), UserInfoEntity::class.java)
gson.fromJson(mmkv.decodeString(KEY_USER_INFO, null), UserInfoEntity::class.java)
?.takeIf { !it.user_id.isNullOrBlank() }
}catch (e: Exception){
null
}
@ -209,4 +210,4 @@ object PreferenceUtil {
fun clearAll() {
mmkv.clearAll()
}
}
}

View File

@ -1,11 +1,9 @@
package com.img.rabbit.provider.utils
import android.util.Log
import com.github.gzuliyujiang.oaid.DeviceIdentifier
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.BuildConfig
import com.img.rabbit.config.Constants
import com.img.rabbit.config.Constants.LOG_REQUEST
import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext
import com.img.rabbit.provider.utils.HeadParamUtils.getAppVersionName
import com.img.rabbit.utils.ChannelUtils
@ -33,22 +31,6 @@ class HeaderInterceptor : Interceptor {
mBuilder.header("x-click-id", "${ChannelUtils.getBdVid(applicationContext)}")
mBuilder.header("x-app-id", Constants.AppId)
val stringBuilder = StringBuilder()
stringBuilder.append("-------------> 📤 header start<-------------\n")
stringBuilder.append("│ x-token = $accessToken\n")
stringBuilder.append("│ x-version = ${getAppVersionName()}\n")
stringBuilder.append("│ x-device-id = ${DeviceIdentifier.getAndroidID(applicationContext)}\n")
stringBuilder.append("│ x-mobile-brand = ${android.os.Build.BRAND}\n")
stringBuilder.append("│ x-mobile-model = ${android.os.Build.MODEL}\n")
stringBuilder.append("│ x-base-version = ${getAppVersionName()}\n")
stringBuilder.append("│ x-channel = ${ChannelUtils.getChannel(applicationContext)}\n")
stringBuilder.append("│ x-click-id = ${ChannelUtils.getBdVid(applicationContext)}\n")
stringBuilder.append("│ x-package = ${BuildConfig.APPLICATION_ID}\n")
stringBuilder.append("-------------> header end <-------------")
Log.i(LOG_REQUEST, stringBuilder.toString())
val request = mBuilder
.method(original.method, original.body)
.build()
@ -72,4 +54,4 @@ class HeaderInterceptor : Interceptor {
return chain.proceed(original)
}
}
}
}

View File

@ -0,0 +1,95 @@
package com.img.rabbit.uni
import android.app.Activity
import android.app.Application
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import android.view.Window
import android.view.WindowManager
import io.dcloud.feature.sdk.DCUniMPActivity
/** 在各 UniMP 进程中维持底部沉浸,覆盖启动图关闭、页面切换和后台返回。 */
@Suppress("DEPRECATION")
object UniMPImmersiveWindow {
fun register(application: Application) {
application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
private val controllers = mutableMapOf<Activity, Controller>()
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
// 包含 DCUniMPActivity0..4 和 DCUniMPTopActivity0..4;不改宿主及支付等页面。
if (activity is DCUniMPActivity) {
controllers[activity] = Controller(activity.window)
}
}
override fun onActivityResumed(activity: Activity) {
controllers[activity]?.apply()
}
override fun onActivityDestroyed(activity: Activity) {
controllers.remove(activity)?.close()
}
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
})
}
internal fun apply(window: Window) {
val flags = window.attributes.flags
if (flags and WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS == 0) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
}
if (flags and WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION != 0) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
}
if (window.navigationBarColor != Color.TRANSPARENT) window.navigationBarColor = Color.TRANSPARENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && window.navigationBarDividerColor != Color.TRANSPARENT) {
window.navigationBarDividerColor = Color.TRANSPARENT
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && window.isNavigationBarContrastEnforced) {
window.isNavigationBarContrastEnforced = false
}
// 只让内容延伸至导航栏下方。保留 SDK 的状态栏、图标颜色和 adjustResize 输入法处理;
// 不隐藏系统手势条,也不消费键盘或状态栏的 WindowInsets。
val decor = window.decorView
val visibility = decor.systemUiVisibility or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
if (decor.systemUiVisibility != visibility) decor.systemUiVisibility = visibility
}
private class Controller(private val window: Window) :
ViewTreeObserver.OnGlobalLayoutListener, ViewTreeObserver.OnWindowFocusChangeListener {
private val decor = window.decorView
private val observer = decor.viewTreeObserver
init {
observer.addOnGlobalLayoutListener(this)
observer.addOnWindowFocusChangeListener(this)
apply()
}
fun apply() = UniMPImmersiveWindow.apply(window)
override fun onGlobalLayout() = apply()
override fun onWindowFocusChanged(hasFocus: Boolean) {
if (hasFocus) apply()
}
fun close() {
// 未附着时注册的 ViewTreeObserver 会合并到附着后的 observer。
val activeObserver = if (observer.isAlive) observer else decor.viewTreeObserver
if (activeObserver.isAlive) {
activeObserver.removeOnGlobalLayoutListener(this)
activeObserver.removeOnWindowFocusChangeListener(this)
}
}
}
}

View File

@ -9,8 +9,9 @@ import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import androidx.core.view.WindowCompat
import io.dcloud.feature.sdk.DCUniMPActivity
/** 只在 UniMP 启动图显示期间让图片延伸到系统导航栏下方。 */
/** 启动图期间设置导航图标明暗,关闭后交由 UniMP 正文的沉浸控制器接管。 */
@Suppress("DEPRECATION")
class UniMPSplashWindow(
context: Context,
@ -19,7 +20,8 @@ class UniMPSplashWindow(
) :
View.OnAttachStateChangeListener, ViewTreeObserver.OnGlobalLayoutListener {
private val window = findActivity(context)?.window
private val activity = findActivity(context)
private val window = activity?.window
private val originalNavigationBarColor = window?.navigationBarColor
private val originalSystemUiVisibility = window?.decorView?.systemUiVisibility ?: 0
private val originalWindowFlags = window?.attributes?.flags ?: 0
@ -81,7 +83,7 @@ class UniMPSplashWindow(
fun close() {
if (closed) return
closed = true
// 先取消监听及延时任务,防止关闭后再次改动小程序正文的窗口。
// 先取消启动图监听及延时任务,正文由独立的沉浸控制器维护。
splashView.removeCallbacks(reapply)
splashView.removeOnAttachStateChangeListener(this)
observer?.takeIf { it.isAlive }?.removeOnGlobalLayoutListener(this)
@ -100,6 +102,8 @@ class UniMPSplashWindow(
originalContrastEnforced?.let { window.isNavigationBarContrastEnforced = it }
}
insetsController?.isAppearanceLightNavigationBars = originalLightNavigationBars
// 启动图关闭时立即接续底部沉浸,避免恢复窗口后先露出一帧安全区底色。
if (activity is DCUniMPActivity) UniMPImmersiveWindow.apply(window)
}
private companion object {

View File

@ -86,8 +86,9 @@ class LoginViewModel : BaseViewModel() {
// 保留最新配置供首页观察;userConfigResult 作为请求完成事件会被 Activity 清空。
private val _userConfig = mutableStateOf(PreferenceUtil.getUserConfig())
val userConfig: State<UserConfigEntity?> = _userConfig
// 用户信息获取结果
val userInfoResult = mutableStateOf<ResultVo<UserInfoEntity>?>(null)
// 页面直接观察用户数据,缓存只用于首次加载。
private val _userInfo = mutableStateOf(PreferenceUtil.getUserInfo())
val userInfo: State<UserInfoEntity?> = _userInfo
// 错误状态
val errorState = mutableStateOf<ErrorBean?>(null)
@ -385,12 +386,18 @@ class LoginViewModel : BaseViewModel() {
}
fun requestUserInfo(){
PreferenceUtil.saveUserInfo(null)
val currentUserId = _userConfig.value?.user_id
if (!currentUserId.isNullOrBlank() && _userInfo.value?.user_id != currentUserId) {
PreferenceUtil.saveUserInfo(null)
_userInfo.value = null
}
mLaunch {
val response = ApiManager.serviceVo.userInfo()
// 切换账号后,忽略旧账号尚未完成的请求。
if (currentUserId != _userConfig.value?.user_id) return@mLaunch
if(response.status){
PreferenceUtil.saveUserInfo(response.data)
userInfoResult.value = response
_userInfo.value = response.data
}
}
}
@ -405,6 +412,7 @@ class LoginViewModel : BaseViewModel() {
val response = ApiManager.serviceVo.logout()
if (response.status) {
PreferenceUtil.clearLogin()
_userInfo.value = null
AppEventBus.post( LoginBindEvent.Login(userId = null, loginType = PreferenceUtil.getLoginType(), isLogin = false, data = null) )
} else {
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "退出登录失败" })