2 Commits

Author SHA1 Message Date
efa96c8e74 修正trtc sdk初始化问题 2024-10-24 17:40:46 +08:00
dbcb4025a6 优化启动速度 2024-10-24 17:17:01 +08:00
11 changed files with 182 additions and 114 deletions

View File

@@ -38,7 +38,7 @@
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.App.Starting"
android:theme="@style/Theme.RiderPro"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

View File

@@ -7,6 +7,7 @@ import android.icu.util.TimeZone
import android.util.Log
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.UserAuth
import com.aiosman.riderpro.ui.favourite.FavouriteListViewModel
import com.aiosman.riderpro.ui.favourite.FavouriteNoticeViewModel
import com.aiosman.riderpro.ui.follower.FollowerNoticeViewModel
@@ -25,6 +26,8 @@ import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMSDKConfig
import com.tencent.imsdk.v2.V2TIMUserFullInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.coroutines.suspendCoroutine
@@ -32,9 +35,26 @@ object AppState {
var UserId: Int? = null
suspend fun initWithAccount(scope: CoroutineScope, context: Context) {
Log.d("AppState", "initWithAccount")
val accountService: AccountService = AccountServiceImpl()
// Declare resp outside the try-catch block
var resp: UserAuth? = null
// 获取用户认证信息
val resp = accountService.getMyAccount()
// 在 IO 线程池中异步执行 getAccount()
withContext(Dispatchers.IO) {
try {
resp = accountService.getMyAccount()
// 账户有效 - No need to explicitly set a flag here
} catch (e: Exception) {
// 处理异常,例如记录日志、显示错误信息等
// 账户无效 - resp will remain null
}
}
// 根据 isAccountValidate 的值来决定后续操作
if (resp != null) {
AppStore.updateLoginState(true)
// ... 账户有效时的操作,例如更新用户信息、注册 JPush 等 ...
// 更新必要的用户信息
val calendar: Calendar = Calendar.getInstance()
val tz: TimeZone = calendar.timeZone
@@ -46,7 +66,10 @@ object AppState {
tz.displayName
)
// 设置当前登录用户 ID
UserId = resp.id
UserId = resp?.id // Access id from the userAuth parameter
// 初始化 JPushManager
JPushManager.init(context)
// 注册 JPush
Messaging.registerDevice(scope, context)
@@ -73,6 +96,10 @@ object AppState {
} catch (e: Exception) {
e.printStackTrace()
}
} else {
// ... 账户无效时的操作 ...
AppStore.updateLoginState(false)
}
}
suspend fun loginToTrtc(userId: String, userSig: String): Boolean {

View File

@@ -0,0 +1,24 @@
package com.aiosman.riderpro
import android.content.Context
import cn.jiguang.api.utils.JCollectionAuth
import cn.jpush.android.api.JPushInterface
object JPushManager {
private var initialized = false
fun init(context: Context) {
if (!initialized) {
JPushInterface.setDebugMode(true)
// 调整点一初始化代码前增加setAuth调用
JCollectionAuth.setAuth(context, true)
JPushInterface.init(context)
initialized = true
}
}
fun getRegistrationID(context: Context): String {
init(context) // 确保 JPush 已经初始化
return JPushInterface.getRegistrationID(context)
}
}

View File

@@ -69,44 +69,32 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 监听应用生命周期
ProcessLifecycleOwner.get().lifecycle.addObserver(MainActivityLifecycleObserver())
// 创建通知渠道
createNotificationChannel()
// 沉浸式状态栏
WindowCompat.setDecorFitsSystemWindows(window, false)
// 初始化 Places SDK
// 初始化 Firebase Analytics
// analytics = Firebase.analytics
// 请求通知权限
askNotificationPermission()
// 加载一些本地化的配置
AppStore.init(this)
JPushInterface.setDebugMode(true);
// 调整点一初始化代码前增加setAuth调用
JCollectionAuth.setAuth(this, true)
JPushInterface.init(this)
enableEdgeToEdge()
// 初始化腾讯云通信 SDK
scope.launch {
// 检查是否有登录态
val isAccountValidate = getAccount()
var startDestination = NavigationRoute.Login.route
// 如果有登录态,且记住登录状态,且账号有效,则初始化 FCM下一步进入首页
if (AppStore.token != null && AppStore.rememberMe && isAccountValidate) {
AppState.initWithAccount(scope, this@MainActivity)
startDestination = NavigationRoute.Index.route
setContent {
// 根据登录状态决定启动页面
val startDestination = if (AppStore.isLoggedIn) {
NavigationRoute.Index.route
} else {
NavigationRoute.Login.route
}
setContent {
Navigation(startDestination) { navController ->
// 处理带有 postId 的通知点击
val postId = intent.getStringExtra("POST_ID")
@@ -121,17 +109,19 @@ class MainActivity : ComponentActivity() {
return@Navigation
}
if (action == "TRTC_NEW_MESSAGE") {
val userService:UserService = UserServiceImpl()
val userService: UserService = UserServiceImpl()
val sender = intent.getStringExtra("SENDER")
sender?.let {
scope.launch {
try {
val profile = userService.getUserProfileByTrtcUserId(it)
navController.navigate(NavigationRoute.Chat.route.replace(
navController.navigate(
NavigationRoute.Chat.route.replace(
"{id}",
profile.id.toString()
))
}catch (e:Exception){
)
)
} catch (e: Exception) {
e.printStackTrace()
}
}
@@ -163,12 +153,8 @@ class MainActivity : ComponentActivity() {
}
}
}
}
}
/**
* 请求通知权限
*/

View File

@@ -24,7 +24,7 @@ object Messaging {
fun registerJpush(scope: CoroutineScope, context: Context) {
val accountService: AccountService = AccountServiceImpl()
val regId = JPushInterface.getRegistrationID(context)
val regId = JPushManager.getRegistrationID(context)
scope.launch {
accountService.registerMessageChannel(client = "jpush", identifier = regId)
}
@@ -32,7 +32,7 @@ object Messaging {
private suspend fun unregisterJpush(context: Context) {
val accountService: AccountService = AccountServiceImpl()
val regId = JPushInterface.getRegistrationID(context)
val regId = JPushManager.getRegistrationID(context)
accountService.unregisterMessageChannel(client = "jpush", identifier = regId)
}

View File

@@ -1,5 +1,6 @@
package com.aiosman.riderpro.data
import android.util.Log
import com.aiosman.riderpro.AppState
import com.aiosman.riderpro.data.api.ApiClient
import com.aiosman.riderpro.data.api.AppConfig
@@ -411,6 +412,7 @@ class AccountServiceImpl : AccountService {
password = password,
captcha = captchaInfo,
))
Log.d("login", resp.toString())
if (!resp.isSuccessful) {
parseErrorResponse(resp.errorBody())?.let {
throw it.toServiceException()

View File

@@ -14,6 +14,11 @@ object AppStore {
var rememberMe: Boolean = false
private lateinit var sharedPreferences: SharedPreferences
lateinit var googleSignInOptions: GoogleSignInOptions
var isLoggedIn: Boolean = false
private set
fun init(context: Context) {
sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
this.loadData()
@@ -25,6 +30,13 @@ object AppStore {
googleSignInOptions = gso
}
fun updateLoginState(isLoggedIn: Boolean) { // 添加更新 isLoggedIn 的方法
this.isLoggedIn = isLoggedIn
sharedPreferences.edit().apply {
putBoolean("isLoggedIn", isLoggedIn)
}.apply()
}
suspend fun saveData() {
// shared preferences
sharedPreferences.edit().apply {
@@ -37,5 +49,6 @@ object AppStore {
// shared preferences
token = sharedPreferences.getString("token", null)
rememberMe = sharedPreferences.getBoolean("rememberMe", false)
isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false)
}
}

View File

@@ -344,7 +344,7 @@ fun ChatSelfItem(item: ChatItem) {
max = (if (item.messageType == V2TIMMessage.V2TIM_ELEM_TYPE_TEXT) 250.dp else 150.dp)
)
.clip(RoundedCornerShape(8.dp))
.background(Color(0xFF000000))
.background(Color(0xFF007FFF))
.padding(
vertical = (if (item.messageType == V2TIMMessage.V2TIM_ELEM_TYPE_TEXT) 8.dp else 0.dp),
horizontal = (if (item.messageType == V2TIMMessage.V2TIM_ELEM_TYPE_TEXT) 16.dp else 0.dp)

View File

@@ -1,5 +1,6 @@
package com.aiosman.riderpro.ui.index
import android.util.Log
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
@@ -26,11 +27,14 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import com.aiosman.riderpro.AppState
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.index.tabs.add.AddPage
import com.aiosman.riderpro.ui.index.tabs.message.MessageListViewModel
import com.aiosman.riderpro.ui.index.tabs.message.NotificationsScreen
import com.aiosman.riderpro.ui.index.tabs.moment.MomentsList
import com.aiosman.riderpro.ui.index.tabs.profile.ProfileWrap
@@ -48,6 +52,7 @@ fun IndexScreen() {
val navigationBarHeight = with(LocalDensity.current) {
WindowInsets.navigationBars.getBottom(this).toDp()
}
val context = LocalContext.current
val navController = LocalNavController.current
val item = listOf(
NavigationItem.Home,
@@ -62,6 +67,11 @@ fun IndexScreen() {
LaunchedEffect(Unit) {
systemUiController.setNavigationBarColor(Color.Transparent)
Log.d("IndexScreen", "IndexScreen: ")
coroutineScope.launch {
AppState.initWithAccount(coroutineScope, context)
MessageListViewModel.initData(context)
}
}
Scaffold(
bottomBar = {

View File

@@ -64,7 +64,6 @@ fun NotificationsScreen() {
})
LaunchedEffect(Unit) {
systemUiController.setNavigationBarColor(Color.Transparent)
MessageListViewModel.initData(context)
}
Column(
modifier = Modifier.fillMaxSize()

View File

@@ -1,5 +1,6 @@
package com.aiosman.riderpro.ui.login
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
@@ -98,6 +99,7 @@ fun UserAuthScreen() {
if (!validateForm()) {
return
}
Log.d("UserAuthScreen", "onLogin: $captchaInfo")
scope.launch {
try {
// 检查是否需要验证码
@@ -106,8 +108,13 @@ fun UserAuthScreen() {
return@launch
}
// 获取用户凭证
Log.d("UserAuthScreen", "loginUserWithPassword")
Log.d("UserAuthScreen", "email: $email")
Log.d("UserAuthScreen", "password: $password")
val authResp = accountService.loginUserWithPassword(email, password, captchaInfo)
if (authResp.token != null) {
Log.d("UserAuthScreen", "authResp.token: ${authResp.token}")
AppStore.updateLoginState(true)
AppStore.apply {
token = authResp.token
this.rememberMe = rememberMe