完善初始化界面

master
pan 4 years ago
parent 18b9ef396f
commit bfdd997ae8
  1. 3
      foreground/src/main/java/com/gyf/csams/Api.kt
  2. 11
      foreground/src/main/java/com/gyf/csams/InitViewModel.kt
  3. 11
      foreground/src/main/java/com/gyf/csams/account/model/AccountViewModel.kt
  4. 3
      foreground/src/main/java/com/gyf/csams/account/ui/AccountActivity.kt
  5. 50
      foreground/src/main/java/com/gyf/csams/main/model/MainViewModel.kt
  6. 11
      foreground/src/main/java/com/gyf/csams/main/ui/MainActivity.kt
  7. 15
      foreground/src/main/java/com/gyf/csams/util/TokenUtil.kt
  8. 17
      lib/src/main/java/com/gyf/lib/util/HttpUtil.kt

@ -20,7 +20,8 @@ enum class AccountApi(val path: String) : UrlPath {
Register("/register"), Register("/register"),
CheckId("/register/checkId"), CheckId("/register/checkId"),
Login("/login"), Login("/login"),
LoginToken("/login/token"); LoginToken("/login/token"),
Logout("/logout");
override fun build(): String { override fun build(): String {

@ -10,10 +10,10 @@ import com.google.gson.reflect.TypeToken
import com.gyf.csams.util.AppDatabase import com.gyf.csams.util.AppDatabase
import com.gyf.csams.util.SimpleCallback import com.gyf.csams.util.SimpleCallback
import com.gyf.csams.util.Token import com.gyf.csams.util.Token
import com.gyf.csams.util.TokenManager
import com.gyf.lib.util.ApiResponse import com.gyf.lib.util.ApiResponse
import com.gyf.lib.util.HttpClient import com.gyf.lib.util.HttpClient
import com.orhanobut.logger.Logger import com.orhanobut.logger.Logger
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
data class TokenVo(val token: String, val studentId: String) data class TokenVo(val token: String, val studentId: String)
@ -38,7 +38,6 @@ class InitViewModel : ViewModel() {
private fun checkServer() { private fun checkServer() {
Logger.i("测试连接到服务端") Logger.i("测试连接到服务端")
viewModelScope.launch { viewModelScope.launch {
delay(5000)
HttpClient.get( HttpClient.get(
Api.buildUrl(TestApi.Test), Api.buildUrl(TestApi.Test),
SimpleCallback<Boolean>(action = "测试", onSuccess = { SimpleCallback<Boolean>(action = "测试", onSuccess = {
@ -72,6 +71,9 @@ class InitViewModel : ViewModel() {
it.body?.let { it.body?.let {
_token.postValue(it) _token.postValue(it)
Logger.i("token校验结果:${it}") Logger.i("token校验结果:${it}")
if (it) {
TokenManager.token = currentToken
}
} }
}, },
@ -86,8 +88,11 @@ class InitViewModel : ViewModel() {
) )
) )
} else if (tokenList != null && tokenList.size > 1) { } else if (tokenList != null && tokenList.size > 1) {
//TODO 实现切换历史登录帐号 //TODO 实现切换历史登录帐号
Logger.i("token数量大于一,需要手动登录") Logger.i("本地存储了${tokenList.size}个令牌,需要手动登录")
db.tokenDao().deleteAll()
Logger.i("清空所有token")
_token.postValue(false) _token.postValue(false)
} else { } else {
Logger.i("本地没有任何token,跳转到登录界面") Logger.i("本地没有任何token,跳转到登录界面")

@ -11,11 +11,12 @@ import com.google.gson.Gson
import com.google.gson.reflect.TypeToken import com.google.gson.reflect.TypeToken
import com.gyf.csams.AccountApi import com.gyf.csams.AccountApi
import com.gyf.csams.Api import com.gyf.csams.Api
import com.gyf.csams.InitActivity
import com.gyf.csams.R import com.gyf.csams.R
import com.gyf.csams.account.ui.AccountRoute import com.gyf.csams.account.ui.AccountRoute
import com.gyf.csams.main.ui.MainActivity
import com.gyf.csams.util.AppDatabase import com.gyf.csams.util.AppDatabase
import com.gyf.csams.util.SimpleCallback import com.gyf.csams.util.SimpleCallback
import com.gyf.csams.util.TokenManager
import com.gyf.csams.util.TokenResDto import com.gyf.csams.util.TokenResDto
import com.gyf.lib.uikit.FormStatus import com.gyf.lib.uikit.FormStatus
import com.gyf.lib.uikit.StringForm import com.gyf.lib.uikit.StringForm
@ -265,15 +266,17 @@ class AccountViewModel(application: Application) : AndroidViewModel(application)
SimpleCallback<Token>( SimpleCallback<Token>(
action = loginDesc, action = loginDesc,
onSuccess = { onSuccess = {
Logger.i(it.message)
callback(it.message) callback(it.message)
val context = getApplication<Application>().applicationContext val context = getApplication<Application>().applicationContext
val token = it.body?.token val token = it.body?.token
if (token != null) { if (token != null) {
val db = AppDatabase.getInstance(context) val db = AppDatabase.getInstance(context)
viewModelScope.launch { viewModelScope.launch {
TokenManager.token = token
db?.tokenDao()?.save(token = token) db?.tokenDao()?.save(token = token)
}.invokeOnCompletion { }.invokeOnCompletion {
context.startActivity(Intent(context, InitActivity::class.java)) context.startActivity(Intent(context, MainActivity::class.java))
_finishLogin.postValue(true) _finishLogin.postValue(true)
} }
} }
@ -281,14 +284,12 @@ class AccountViewModel(application: Application) : AndroidViewModel(application)
onFail = { callback(it) }, onFail = { callback(it) },
type = object : TypeToken<ApiResponse<Token>>() {}.type type = object : TypeToken<ApiResponse<Token>>() {}.type
), ),
jsonBody = Gson().toJson( param = UserLoginVo(
UserLoginVo(
studentId = studentId, studentId = studentId,
password = password, password = password,
device = "${Build.MANUFACTURER} ${Build.MODEL}" device = "${Build.MANUFACTURER} ${Build.MODEL}"
) )
) )
)
} else { } else {
Logger.wtf("表单校验失败,无法$loginDesc!!!") Logger.wtf("表单校验失败,无法$loginDesc!!!")
} }

@ -138,12 +138,13 @@ class AccountActivity : ComponentActivity() {
modifier = Modifier.fillMaxSize() modifier = Modifier.fillMaxSize()
) { ) {
Column(modifier = Modifier.width(IntrinsicSize.Min)) { Column(modifier = Modifier.width(IntrinsicSize.Min)) {
val name by accountViewModel.name.formValue.observeAsState("")
Text(buildAnnotatedString { Text(buildAnnotatedString {
withStyle( withStyle(
style = MaterialTheme.typography.subtitle1.toSpanStyle() style = MaterialTheme.typography.subtitle1.toSpanStyle()
.copy(color = MaterialTheme.colors.primary) .copy(color = MaterialTheme.colors.primary)
) { ) {
append(accountViewModel.name.formValue.value ?: "") append(name)
} }
withStyle(style = MaterialTheme.typography.subtitle1.toSpanStyle()) { withStyle(style = MaterialTheme.typography.subtitle1.toSpanStyle()) {
append(accountViewModel.welcomeStart) append(accountViewModel.welcomeStart)

@ -1,14 +1,25 @@
package com.gyf.csams.main.model package com.gyf.csams.main.model
import android.app.Activity
import android.content.Intent
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.google.gson.reflect.TypeToken
import com.gyf.csams.AccountApi
import com.gyf.csams.Api
import com.gyf.csams.NOT_IMPL_TIP import com.gyf.csams.NOT_IMPL_TIP
import com.gyf.csams.account.ui.AccountActivity
import com.gyf.csams.uikit.SendInterface import com.gyf.csams.uikit.SendInterface
import com.gyf.csams.util.AppDatabase
import com.gyf.csams.util.SimpleCallback
import com.gyf.csams.util.TokenManager
import com.gyf.lib.ScrollList import com.gyf.lib.ScrollList
import com.gyf.lib.uikit.PersonInfoVo import com.gyf.lib.uikit.PersonInfoVo
import com.gyf.lib.uikit.StringForm import com.gyf.lib.uikit.StringForm
import com.gyf.lib.util.ApiResponse
import com.gyf.lib.util.HttpClient
import com.gyf.lib.util.randomChinese import com.gyf.lib.util.randomChinese
import com.gyf.lib.util.randomNum import com.gyf.lib.util.randomNum
import com.orhanobut.logger.Logger import com.orhanobut.logger.Logger
@ -173,6 +184,8 @@ data class InfoVo(
override val desc: String override val desc: String
) : PersonInfoVo() ) : PersonInfoVo()
data class UserLogoutVo(val studentId: String)
/** /**
* 个人中心 * 个人中心
* *
@ -202,4 +215,41 @@ class CenterViewModel : ViewModel() {
} }
} }
fun logout(context: Activity, callback: (message: String) -> Unit) {
val studentId = TokenManager.token?.studentId
if (studentId != null) {
Logger.i("帐号$studentId 将要退出登录")
viewModelScope.launch {
HttpClient.post(Api.buildUrl(AccountApi.Logout),
SimpleCallback<Boolean>(action = "登出", onSuccess = { it ->
it.body?.let {
if (it) {
viewModelScope.launch {
val db = AppDatabase.getInstance(context = context)
db?.tokenDao()?.deleteAll()
Logger.i("退出登陆成功")
context.finish()
context.startActivity(
Intent(
context,
AccountActivity::class.java
)
)
}
TokenManager.token = null
}
}
callback(it.message)
}, onFail = { callback("退出登陆失败") },
type = object : TypeToken<ApiResponse<Boolean>>() {}.type
),
param = UserLogoutVo(studentId = studentId)
)
}
} else {
callback("操作异常,请联系管理员")
}
}
} }

@ -52,7 +52,7 @@ class MainActivity : ComponentActivity() {
setContent { setContent {
Body { nav -> TestBody { nav, s ->
NavHost(navController = nav, startDestination = MainMenu.Main.name) { NavHost(navController = nav, startDestination = MainMenu.Main.name) {
composable(MainMenu.Main.name) { composable(MainMenu.Main.name) {
Main(navController = nav) Main(navController = nav)
@ -62,6 +62,7 @@ class MainActivity : ComponentActivity() {
} }
composable(MainMenu.Center.name) { composable(MainMenu.Center.name) {
Center(navController = nav) Center(navController = nav)
ShowSnackbar(scaffoldState = s)
} }
} }
@ -90,6 +91,7 @@ class MainActivity : ComponentActivity() {
@Composable @Composable
private fun Center( private fun Center(
model: CenterViewModel = viewModel(), model: CenterViewModel = viewModel(),
scaffoldModel: ScaffoldModel = viewModel(),
navController: NavHostController navController: NavHostController
) { ) {
MainColumnFrame( MainColumnFrame(
@ -97,7 +99,7 @@ class MainActivity : ComponentActivity() {
mainMenu = MainMenu.Center, mainMenu = MainMenu.Center,
nav = navController nav = navController
) { ) {
val context = LocalContext.current val context = LocalContext.current as MainActivity
val info by model.info.observeAsState() val info by model.info.observeAsState()
@ -121,6 +123,11 @@ class MainActivity : ComponentActivity() {
CenterMenuItem(text = model.myJoinActivity) CenterMenuItem(text = model.myJoinActivity)
CenterMenuItem(text = model.myLikeActivity) CenterMenuItem(text = model.myLikeActivity)
CenterMenuItem(text = model.myCollectActivity) CenterMenuItem(text = model.myCollectActivity)
CenterMenuItem(text = "退出登录") {
model.logout(context = context) {
scaffoldModel.update(message = it)
}
}
} }
} }

@ -34,20 +34,13 @@ interface TokenDao {
@Delete @Delete
suspend fun delete(user: Token) suspend fun delete(user: Token)
}
class TokenManager private constructor(private var token: Token?) {
companion object {
@Volatile
private var instance: TokenManager? = null
fun getInstance(token: Token? = null) =
instance ?: synchronized(this) {
instance ?: TokenManager(token).also { instance = it }
}
@Query("delete from token")
suspend fun deleteAll()
} }
object TokenManager {
var token: Token? = null
} }

@ -14,6 +14,8 @@ object HttpClient {
private val JSON_CONTENT_TYPE = "application/json; charset=UTF-8".toMediaType() private val JSON_CONTENT_TYPE = "application/json; charset=UTF-8".toMediaType()
private val json = Gson()
/** /**
* 构建url查询参数 * 构建url查询参数
* *
@ -89,6 +91,10 @@ object HttpClient {
* @param callback * @param callback
* @param jsonBody * @param jsonBody
*/ */
@Deprecated(
message = "",
replaceWith = ReplaceWith("com.gyf.lib.util.HttpClient.post(java.lang.String, okhttp3.Callback, java.lang.Object)")
)
fun post(url: String, callback: Callback, jsonBody: String) { fun post(url: String, callback: Callback, jsonBody: String) {
Logger.json(jsonBody) Logger.json(jsonBody)
val request = Request.Builder() val request = Request.Builder()
@ -99,7 +105,16 @@ object HttpClient {
call.enqueue(callback) call.enqueue(callback)
} }
fun post(url: String, callback: Callback, param: Any) {
val jsonBody = json.toJson(param)
Logger.json(jsonBody)
val request = Request.Builder()
.url(url)
.post(body = jsonBody.toRequestBody(contentType = JSON_CONTENT_TYPE))
.build()
val call = httpClient.newCall(request)
call.enqueue(callback)
}
} }
/** /**

Loading…
Cancel
Save