1、代码优化处理
This commit is contained in:
shenzuqiang 2026-03-09 10:53:09 +08:00
parent f5aa72bb3a
commit 4ccb9c8a9a
13 changed files with 78 additions and 116 deletions

Binary file not shown.

View File

@ -84,7 +84,6 @@ import com.img.rabbit.viewmodel.SplashViewModel
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.system.exitProcess
@ -103,19 +102,24 @@ class MainActivity : ComponentActivity(), LoadingCallback {
setContent {
val coroutineScope = rememberCoroutineScope()
val splashViewModel: SplashViewModel = viewModel()
generalViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application))[GeneralViewModel::class.java]
var loginViewModel: LoginViewModel = viewModel()
val context = LocalContext.current
var showSplash by remember { mutableStateOf(false) }
var globalBind by mutableStateOf(GlobalStateManager(context).globalBindNotifyFlow().collectAsState(initial = false))
var globalUnBind by mutableStateOf(GlobalStateManager(context).globalUnBindNotifyFlow().collectAsState(initial = false))
var globalUpdate by mutableStateOf(GlobalStateManager(context).globalUpdateNotifyFlow().collectAsState(initial = false))
val globalUniUpdate by GlobalStateManager(context).globalUniUpdateNotifyFlow().collectAsState(initial = false)
val globalUniDownload by GlobalStateManager(context).globalUniDownloadNotifyFlow().collectAsState(initial = false)
val globalLoading by GlobalStateManager(context).isGlobalLoadingFlow().collectAsState(initial = false)
val context = LocalContext.current
val loginViewModel: LoginViewModel = viewModel()
val splashViewModel: SplashViewModel = viewModel()
generalViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application))[GeneralViewModel::class.java]
var updateAppNotify by mutableStateOf(GlobalStateManager(context).globalUpdateNotifyFlow().collectAsState(initial = false))
val updateUniDownloadNotify by GlobalStateManager(context).globalUniDownloadNotifyFlow().collectAsState(initial = false)
val updateUserConfigNotify by GlobalStateManager(context).globalUserConfigNotifyFlow().collectAsState(initial = false)
val updateUniUpdateNotify by GlobalStateManager(context).globalUniUpdateNotifyFlow().collectAsState(initial = false)
val updateGlobalLoadingNotify by GlobalStateManager(context).isGlobalLoadingFlow().collectAsState(initial = false)
// 设置启动页显示条件
splashScreen.setKeepOnScreenCondition {
splashViewModel.isLoading.value // 当为 true 时,启动页不消失
}
LaunchedEffect(generalViewModel.agreementStatus.value) {
if (generalViewModel.agreementStatus.value == true){
@ -141,36 +145,11 @@ class MainActivity : ComponentActivity(), LoadingCallback {
}
}
// 设置启动页显示条件
splashScreen.setKeepOnScreenCondition {
splashViewModel.isLoading.value // 当为 true 时,启动页不消失
}
// 绑定成功后2秒后自动更新状态
if(globalBind.value == true){
GlobalScope.launch {
//延迟2秒方便处理多有事件都收到通知
delay(2*1000)
GlobalStateManager(context).storeGlobalBindNotify(false)
}
}
// 解绑成功后2秒后自动更新状态
if(globalUnBind.value == true){
GlobalScope.launch {
//延迟2秒方便处理多有事件都收到通知
delay(2*1000)
GlobalStateManager(context).storeGlobalUnBindNotify(false)
}
}
// 处理全局事件类似与EventBus订阅
LaunchedEffect(Unit) {
AppEventBus.events.collect { event ->
when (event) {
is LoginBindEvent.Login -> {
Log.i("AppEventBus","--------------登录成功,开始获取配置和个人数据")
if(!event.isLogin){
loginViewModel.reset()
}
@ -183,6 +162,16 @@ class MainActivity : ComponentActivity(), LoadingCallback {
}
}
//还原全局用户配置通知
LaunchedEffect(updateUserConfigNotify) {
delay(300)
if(updateUserConfigNotify == true){
coroutineScope.launch {
GlobalStateManager(context).storeGlobalUserConfigNotify(false)
}
}
}
AppTheme {
SplashScreenContent{
//未同意提示政策弹窗
@ -236,7 +225,7 @@ class MainActivity : ComponentActivity(), LoadingCallback {
//提示下载小程序资源(在跳转指定页面时,未下载资源需要提示)
val progressWGTToPageState = mutableFloatStateOf(0f)
if(globalUniDownload == true){
if(updateUniDownloadNotify == true){
UniAppUtils.currentDownloadUniMp?.let {
UniAppUtils.downloadReleaseWgt(
coroutineScope,
@ -295,7 +284,7 @@ class MainActivity : ComponentActivity(), LoadingCallback {
//UniApp更新提示
val isDownloadingWGT = mutableStateOf(false)
val progressWGTState = mutableFloatStateOf(0f)
if(globalUniUpdate == true){
if(updateUniUpdateNotify == true){
UniAppUtils.currentUpdateUniMp?.let {
TipsUniMpDialog(
title = "资源包更新",
@ -321,7 +310,7 @@ class MainActivity : ComponentActivity(), LoadingCallback {
//App更新提示
val isStartDownload = mutableStateOf(false)
val progressState = mutableFloatStateOf(0f)
if(globalUpdate.value == true){
if(updateAppNotify.value == true){
UpdateDialog(
title = PreferenceUtil.getUserConfig()?.config?.versionEntity?.title?:"新版本,更新提示",
newVersion = "V${PreferenceUtil.getUserConfig()?.config?.versionEntity?.version}",
@ -362,7 +351,7 @@ class MainActivity : ComponentActivity(), LoadingCallback {
}
//全局加载提示
if (globalLoading == true) {
if (updateGlobalLoadingNotify == true) {
Log.i("HomeScreen","isStartOn--->${System.currentTimeMillis()}")
Box(
modifier = Modifier
@ -570,6 +559,7 @@ private fun PrivacyPolicyScreen(viewModel: LoginViewModel, onAgreementChange: (B
)
}
@Suppress("DEPRECATION")
ClickableText(
text = annotatedText,
modifier = Modifier

View File

@ -76,6 +76,11 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
LaunchedEffect(navBackStackEntry) {
// 当返回到MineScreen页面时执行的操作
if (navBackStackEntry?.destination?.route == "home") {
selectedTab = TabItem.Home
// 显示TabBar
generalViewModel.setNavigationBarVisible(true)
}else if(navBackStackEntry?.destination?.route == "mine"){
selectedTab = TabItem.Mine
// 显示TabBar
generalViewModel.setNavigationBarVisible(true)
}
@ -190,7 +195,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
// 设置页面Setting
composable(ScreenRoute.BindAccount.route) {
AccountBindScreen(navController = navController, loginViewModel = loginViewModel)
AccountBindScreen(navController = navController)
}
composable(ScreenRoute.ManagerAccount.route) {
AccountManagerScreen(navController = navController, loginViewModel = loginViewModel)

View File

@ -64,7 +64,6 @@ import com.img.rabbit.utils.UniMpUpdate
import com.img.rabbit.utils.UniMpWXPayEvent
import com.img.rabbit.viewmodel.GeneralViewModel
import io.dcloud.feature.sdk.DCUniMPSDK
import io.dcloud.feature.unimp.DCUniMPJSCallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.json.JSONObject
@ -76,6 +75,7 @@ fun HomeScreen(
generalViewModel: GeneralViewModel,
loadingCallback: LoadingCallback?
) {
val TAG = "Rabbit_HomeScreen"
val context = LocalContext.current
val scope: CoroutineScope = rememberCoroutineScope()
val progressPair = mutableStateMapOf<String, Float>()
@ -87,13 +87,12 @@ fun HomeScreen(
var lastClickTime by remember { mutableLongStateOf(0L) }
val globalUserConfig by GlobalStateManager(context).globalUserConfigNotifyFlow().collectAsState(initial = false)
val updateUserConfigNotify by GlobalStateManager(context).globalUserConfigNotifyFlow().collectAsState(initial = false)
BackHandler(enabled = (currentRoute == ScreenRoute.Home.route)) {
val currentTime = System.currentTimeMillis()
if (currentTime - lastClickTime > 2000) {
Toast.makeText(context, "再按一次退出应用", Toast.LENGTH_SHORT).show()
Log.i("BackHandler", "HomeScreen----->BackHandler")
lastClickTime = currentTime
} else {
(context as? Activity)?.finish()
@ -131,14 +130,14 @@ fun HomeScreen(
}
}
var homeIconConfig by remember { mutableStateOf(PreferenceUtil.getUserConfig()?.config?.homeIconEntity) }
var uniVersionConfig by remember { mutableStateOf(PreferenceUtil.getUserConfig()?.config?.uniVersionEntity) }
LaunchedEffect(globalUserConfig) {
if(globalUserConfig == true){
LaunchedEffect(updateUserConfigNotify) {
if(updateUserConfigNotify == true){
homeIconConfig = PreferenceUtil.getUserConfig()?.config?.homeIconEntity
uniVersionConfig = PreferenceUtil.getUserConfig()?.config?.uniVersionEntity
Log.i(TAG,"-------------->HomeScreen页面用户配置已经刷新")
}
}
@ -205,7 +204,7 @@ fun HomeScreen(
context,
scope,
uniMp
) { uniState, filePath, progress ->
) { uniState, _, progress ->
progressPair[uniMpId]
?: mutableMapOf<String, Float>().apply {
put(
@ -335,7 +334,7 @@ fun HomeScreen(
context,
scope,
uniMp
) { uniState, filePath, progress ->
) { uniState, _, progress ->
progressPair[uniMpId]
?: mutableMapOf<String, Float>().apply {
put(

View File

@ -15,7 +15,6 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
@ -23,7 +22,6 @@ 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.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
@ -35,12 +33,10 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@ -72,11 +68,8 @@ fun MineScreen(
val TAG = "Rabbit_Mine"
val context = LocalContext.current
val scope = rememberCoroutineScope()
// var globalLogin by mutableStateOf(GlobalStateManager(context).globalLoginNotifyFlow().collectAsState(initial = false))
var globalBind by mutableStateOf(GlobalStateManager(context).globalBindNotifyFlow().collectAsState(initial = false))
var globalUnBind by mutableStateOf(GlobalStateManager(context).globalUnBindNotifyFlow().collectAsState(initial = false))
var updateUserConfigNotify by mutableStateOf(GlobalStateManager(context).globalUserConfigNotifyFlow().collectAsState(initial = false))
//val vipMember by remember { mutableStateOf(false) }
var userInfo by remember { mutableStateOf(PreferenceUtil.getUserInfo()) }
// 获取当前路由状态
@ -89,27 +82,19 @@ fun MineScreen(
val currentTime = System.currentTimeMillis()
if (currentTime - lastClickTime > 2000) {
Toast.makeText(context, "再按一次退出应用", Toast.LENGTH_SHORT).show()
Log.i("BackHandler", "MineScreen----->BackHandler")
lastClickTime = currentTime
} else {
(context as? Activity)?.finish()
}
}
LaunchedEffect(navBackStackEntry) {
// 当返回到MineScreen页面时执行的操作
if (navBackStackEntry?.destination?.route == "mine") {
// 显示TabBar
generalViewModel.setNavigationBarVisible(true)
}
}
//刷新用户信息
// if(globalLogin.value == true || globalBind.value == true || globalUnBind.value == true){
if(globalBind.value == true || globalUnBind.value == true){
if(updateUserConfigNotify.value == true){
scope.launch {
delay(300)
delay(200)
userInfo = PreferenceUtil.getUserInfo()
Log.i(TAG,"-------------->MineScreen页面用户配置已经刷新")
}
}

View File

@ -46,15 +46,15 @@ import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.img.rabbit.R
import com.img.rabbit.pages.toolbar.TitleBar
import com.img.rabbit.provider.storage.GlobalStateManager
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.utils.AppEventBus
import com.img.rabbit.utils.LoginBindEvent
import com.img.rabbit.viewmodel.AccountBindViewModel
import com.img.rabbit.viewmodel.BindViewModel
import com.img.rabbit.viewmodel.LoginViewModel
@SuppressLint("UnrememberedMutableState")
@Composable
fun AccountBindScreen(navController: NavHostController, viewModel: AccountBindViewModel = viewModel(), loginViewModel: LoginViewModel) {
fun AccountBindScreen(navController: NavHostController, viewModel: AccountBindViewModel = viewModel()) {
val context = LocalContext.current
/**
* 0:m默认未绑定1:已绑定手机号去解绑2:已绑定微信去解绑
@ -65,11 +65,17 @@ fun AccountBindScreen(navController: NavHostController, viewModel: AccountBindVi
LaunchedEffect(viewModel.unBindState.value) {
if(viewModel.unBindState.value != null){
val loginInfo = viewModel.unBindState.value?.data
Toast.makeText(context, "解绑成功!", Toast.LENGTH_SHORT).show()
AppEventBus.post( LoginBindEvent.Bind(userId = loginInfo?.user_id?:"", loginType = null, isBind = false, data = loginInfo) )
val popped = navController.popBackStack(route = "home", inclusive = true)
if (!popped) {
navController.navigate("home") {
popUpTo(navController.graph.startDestinationId) { inclusive = true }
}
}
viewModel.unBindState.value = null
GlobalStateManager(context).storeGlobalUnBindNotify(true)
navController.popBackStack()
}
}
LaunchedEffect(viewModel.errorState.value) {
@ -458,7 +464,7 @@ private fun UnBindPhoneDialog(
@Preview(showBackground = true)
@Composable
private fun PreviewAccountBindScreen(){
AccountBindScreen(navController = rememberNavController(), loginViewModel = LoginViewModel())
AccountBindScreen(navController = rememberNavController())
}
@SuppressLint("UnrememberedMutableState")

View File

@ -34,7 +34,6 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
@ -117,9 +116,10 @@ fun BindScreen(navController: NavHostController, viewModel: BindViewModel = view
// 登录成功后,保存 token
LaunchedEffect(viewModel.bindState.value) {
if (viewModel.bindState.value != null && viewModel.bindState.value?.data?.token != null) {
val loginInfo = viewModel.bindState.value?.data
Toast.makeText(context, "绑定成功!", Toast.LENGTH_SHORT).show()
AppEventBus.post( LoginBindEvent.Bind(userId = loginInfo?.user_id?:"", loginType = null, isBind = true, data = loginInfo) )
GlobalStateManager(context).storeGlobalBindNotify(true)
navController.popBackStack()
}else if (viewModel.bindState.value != null){
Toast.makeText(context, "绑定失败!", Toast.LENGTH_SHORT).show()

View File

@ -20,8 +20,6 @@ class GlobalStateManager(
) {
companion object {
private val GLOBAL_LOADING = booleanPreferencesKey("global_loading")
private val GLOBAL_BIND_NOTIFY = booleanPreferencesKey("global_bind_notify")
private val GLOBAL_UNBIND_NOTIFY = booleanPreferencesKey("global_unbind_notify")
private val GLOBAL_UPDATE_NOTIFY = booleanPreferencesKey("global_update_notify")
private val GLOBAL_UNI_UPDATE_NOTIFY = booleanPreferencesKey("global_uni_update_notify")
private val GLOBAL_UNI_DOWNLOAD_NOTIFY = booleanPreferencesKey("global_uni_download_notify")
@ -40,31 +38,6 @@ class GlobalStateManager(
}
}
suspend fun storeGlobalBindNotify(value: Boolean) {
context.storeData.edit { preferences ->
preferences[GLOBAL_BIND_NOTIFY] = value
}
}
fun globalBindNotifyFlow(): Flow<Boolean?> {
return context.storeData.data.map {
preferences ->
preferences[GLOBAL_BIND_NOTIFY]
}
}
suspend fun storeGlobalUnBindNotify(value: Boolean) {
context.storeData.edit { preferences ->
preferences[GLOBAL_UNBIND_NOTIFY] = value
}
}
fun globalUnBindNotifyFlow(): Flow<Boolean?> {
return context.storeData.data.map {
preferences ->
preferences[GLOBAL_UNBIND_NOTIFY]
}
}
suspend fun storeGlobalUpdateNotify(value: Boolean) {
context.storeData.edit { preferences ->

View File

@ -81,8 +81,13 @@ object PreferenceUtil {
return mmkv.decodeBool(KEY_AGREEMENT, false)
}
fun saveUserConfig(config: UserConfigEntity) {
val resultJson = Gson().toJson(config)
fun saveUserConfig(config: UserConfigEntity?) {
val resultJson = if(config == null){
"{}"
}else{
Gson().toJson(config)
}
mmkv.encode(KEY_USER_CONFIG, resultJson)
}

View File

@ -42,7 +42,7 @@ sealed class LoginBindEvent {
* 处理绑定与解绑isBindtrue 绑定false 解绑
* 绑定类型LoginScreenType仅包含手机LoginScreenType.LOGIN_CAPTCHA和微信LoginScreenType.LOGIN_WX
*/
data class Bind(val userId: String, val loginType: LoginScreenType, val isBind: Boolean) : LoginBindEvent()
data class Bind(val userId: String, val loginType: LoginScreenType?, val isBind: Boolean, val data: Any?) : LoginBindEvent()
}

View File

@ -7,7 +7,6 @@ import com.github.gzuliyujiang.oaid.DeviceIdentifier
import com.img.rabbit.BuildConfig
import com.img.rabbit.bean.response.UniVersionEntity
import com.img.rabbit.config.Constants
import com.img.rabbit.config.Constants.LOG_REQUEST
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.provider.storage.PreferenceUtil.getBDVID
import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext
@ -20,7 +19,6 @@ import io.dcloud.feature.sdk.Interface.IUniMP
import io.dcloud.feature.unimp.config.UniMPOpenConfiguration
import io.dcloud.feature.unimp.config.UniMPReleaseConfiguration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
@ -227,7 +225,7 @@ object UniAppUtils {
downloadUniMp(scope, uniVersion){uniState, filePath, progress ->
onProgress(uniState, filePath, progress)
if(uniState == UniMpUpdate.DOWNLOAD_FINISH){
distributeUniMp(context, uniVersion) { loading ->}
distributeUniMp(context, uniVersion) { _ ->}
}
}
}

View File

@ -1,7 +1,6 @@
package com.img.rabbit.viewmodel
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
@ -15,7 +14,6 @@ import android.net.NetworkRequest
import android.os.Build
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.ContextCompat.registerReceiver
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
@ -23,7 +21,6 @@ import com.img.rabbit.config.Constants
import com.img.rabbit.provider.api.ApiManager
import com.img.rabbit.provider.storage.PreferenceUtil
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.DelicateCoroutinesApi

View File

@ -35,6 +35,7 @@ import com.tencent.mm.opensdk.openapi.IWXAPI
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
@ -115,6 +116,8 @@ class LoginViewModel : BaseViewModel() {
fun requestUserConfig(){
mLaunch {
//先置空配置
PreferenceUtil.saveUserConfig(null)
val oaid = MMKVUtils.getString("oaid") ?: ""
val response = ApiManager.serviceVo.getUserConfig(oaid, Build.VERSION.SDK_INT, "", DeviceIdentifier.getAndroidID(applicationContext), MMKVUtils.getString("gt_cid") ?: "")
if (response.status) {
@ -123,6 +126,7 @@ class LoginViewModel : BaseViewModel() {
PreferenceUtil.saveUserConfig(response.data)
userConfigResult.value = response
//以下是刷新状态
applicationContext?.let { GlobalStateManager(it) }?.storeGlobalUserConfigNotify(true)
}else{
Log.w("LoginViewModel", "获取配置失败: code=${response.code}, message=${response.message}")