1、添加下载逻辑优化、小程序启动逻辑及解码释放
2、导航高度处理
3、一键登陆处理
This commit is contained in:
Elemt 2026-11-02 11:34:48 +08:00
parent 0fb4127d7a
commit 0268068f86
21 changed files with 983 additions and 579 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="CompilerConfiguration"> <component name="CompilerConfiguration">
<bytecodeTargetLevel target="21" /> <bytecodeTargetLevel target="25" />
</component> </component>
</project> </project>

View File

@ -13,6 +13,39 @@
</DropdownSelection> </DropdownSelection>
<DialogSelection /> <DialogSelection />
</SelectionState> </SelectionState>
<SelectionState runConfigName="main">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=JRBI89BIE6AI5TG6" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
<SelectionState runConfigName="unitTest">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=JRBI89BIE6AI5TG6" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
<SelectionState runConfigName="androidTest">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=JRBI89BIE6AI5TG6" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
</selectionStates> </selectionStates>
</component> </component>
</project> </project>

View File

@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" /> <component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="jbr-25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>
<component name="ProjectType"> <component name="ProjectType">

View File

@ -27,6 +27,8 @@ import java.lang.Exception
class BaseApplication : Application() { class BaseApplication : Application() {
private val TAG = "BaseApplication" private val TAG = "BaseApplication"
private var uniAppInitialized = false
private var uniAppOaid: String? = null
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
@ -114,7 +116,11 @@ class BaseApplication : Application() {
//初始化uni-app SDK //初始化uni-app SDK
private fun initUniAPPSdk() { private fun initUniAPPSdk() {
if (isMainProcess(this)) { if (PreferenceUtil.getAgreement() && isMainProcess(this)) {
val oaid = PreferenceUtil.getOAID()
if (uniAppInitialized && uniAppOaid == oaid) return
uniAppInitialized = true
uniAppOaid = oaid
val item = MenuActionSheetItem("关于", "gy") val item = MenuActionSheetItem("关于", "gy")
val item1 = MenuActionSheetItem("获取当前页面url", "hqdqym") val item1 = MenuActionSheetItem("获取当前页面url", "hqdqym")
val item2 = MenuActionSheetItem("跳转到宿主原生测试页面", "gotoTestPage") val item2 = MenuActionSheetItem("跳转到宿主原生测试页面", "gotoTestPage")
@ -123,15 +129,19 @@ class BaseApplication : Application() {
sheetItems.add(item1) sheetItems.add(item1)
sheetItems.add(item2) sheetItems.add(item2)
val config: DCSDKInitConfig? = DCSDKInitConfig.Builder() val config: DCSDKInitConfig? = DCSDKInitConfig.Builder()
.setCapsule(true) .setCapsule(false)
.setMenuDefFontSize("16px") .setMenuDefFontSize("16px")
.setMenuDefFontColor("#ff00ff") .setMenuDefFontColor("#ff00ff")
.setMenuDefFontWeight("normal") .setMenuDefFontWeight("normal")
.setMenuActionSheetItems(sheetItems) .setMenuActionSheetItems(sheetItems)
.setCustomOAID(PreferenceUtil.getOAID()) .setCustomOAID(PreferenceUtil.getOAID())
.setEnableBackground(false) .setEnableBackground(false)
.setUniMPFromRecents(true)
.build() .build()
DCUniMPSDK.getInstance().initialize(this, config) DCUniMPSDK.getInstance().initialize(this, config) { success ->
uniAppInitialized = success
Log.d("UniMP", "onInitFinished: $success")
}
} }
} }
@ -151,4 +161,4 @@ class BaseApplication : Application() {
} }
} }

View File

@ -1,7 +1,6 @@
package com.img.rabbit package com.img.rabbit
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
@ -63,7 +62,6 @@ import com.img.rabbit.config.Constants.agreementUrl
import com.img.rabbit.config.Constants.privacyUrl import com.img.rabbit.config.Constants.privacyUrl
import com.img.rabbit.pages.LoadingCallback import com.img.rabbit.pages.LoadingCallback
import com.img.rabbit.pages.LoginScreen import com.img.rabbit.pages.LoginScreen
import com.img.rabbit.pages.LoginScreenType
import com.img.rabbit.pages.MainScreen import com.img.rabbit.pages.MainScreen
import com.img.rabbit.pages.dialog.TipsDialog import com.img.rabbit.pages.dialog.TipsDialog
import com.img.rabbit.pages.dialog.TipsUniMpDialog import com.img.rabbit.pages.dialog.TipsUniMpDialog
@ -125,9 +123,11 @@ class MainActivity : ComponentActivity(), LoadingCallback {
// 下载小程序资源(在跳转指定页面时,未下载资源需要提示) // 下载小程序资源(在跳转指定页面时,未下载资源需要提示)
var showUniDownloadDialog by remember { mutableStateOf(false) } var showUniDownloadDialog by remember { mutableStateOf(false) }
var downloadUniEntity by remember { mutableStateOf<UniVersionEntity?>(null) } var downloadUniEntity by remember { mutableStateOf<UniVersionEntity?>(null) }
var downloadUniPagePath by remember { mutableStateOf<String?>(null) }
// 小程序资源更新提示 // 小程序资源更新提示
var showUniUpdateDialog by remember { mutableStateOf(false) } var showUniUpdateDialog by remember { mutableStateOf(false) }
var updateUniEntity by remember { mutableStateOf<UniVersionEntity?>(null) } var updateUniEntity by remember { mutableStateOf<UniVersionEntity?>(null) }
var updateUniPagePath by remember { mutableStateOf<String?>(null) }
//以下为流事件收集订阅 //以下为流事件收集订阅
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
GlobalEventBus.events.collect { event -> GlobalEventBus.events.collect { event ->
@ -142,11 +142,13 @@ class MainActivity : ComponentActivity(), LoadingCallback {
// 小程序资源下载提示 // 小程序资源下载提示
is GlobalEvent.ShowUniDownloadNotify -> { is GlobalEvent.ShowUniDownloadNotify -> {
downloadUniEntity = event.entity downloadUniEntity = event.entity
downloadUniPagePath = event.pagePath
showUniDownloadDialog = true showUniDownloadDialog = true
} }
// 小程序资源更新提示 // 小程序资源更新提示
is GlobalEvent.ShowUniUpdateNotify -> { is GlobalEvent.ShowUniUpdateNotify -> {
updateUniEntity = event.entity updateUniEntity = event.entity
updateUniPagePath = event.pagePath
showUniUpdateDialog = true showUniUpdateDialog = true
} }
// 登录提示 // 登录提示
@ -210,6 +212,8 @@ class MainActivity : ComponentActivity(), LoadingCallback {
LaunchedEffect(showUniDownloadDialog) { LaunchedEffect(showUniDownloadDialog) {
if(showUniDownloadDialog) { if(showUniDownloadDialog) {
downloadUniEntity?.let{ downloadUniEntity?.let{
val downloadVersion = it
val downloadPagePath = downloadUniPagePath
UniAppUtils.downloadReleaseWgt( UniAppUtils.downloadReleaseWgt(
coroutineScope, coroutineScope,
it, it,
@ -251,16 +255,7 @@ class MainActivity : ComponentActivity(), LoadingCallback {
onRelease = { isSuccess-> onRelease = { isSuccess->
if(isSuccess){ if(isSuccess){
//资源下载完成后,启动小程序到指定位置 //资源下载完成后,启动小程序到指定位置
val uniMpEntity = downloadUniEntity UniAppUtils.distributeUniMp(context, downloadVersion, reportViewModel, downloadPagePath) {}
if (uniMpEntity != null && UniAppUtils.isRelease(uniMpEntity.unimp_id)) {
UniAppUtils.startUniMpPage(
context = context,
uniMpId = uniMpEntity.unimp_id,
uniMpType = uniMpEntity.unimp_type,
pagePath = UniAppUtils.currentUniMpJumpPatch ?: "",
reportViewModel = reportViewModel
)
}
} }
}, },
reportViewModel = reportViewModel reportViewModel = reportViewModel
@ -300,16 +295,6 @@ class MainActivity : ComponentActivity(), LoadingCallback {
// 未登录,显示登录页 // 未登录,显示登录页
//if (token.isNullOrEmpty() && loginViewModel.userConfigResult.value == null) { //if (token.isNullOrEmpty() && loginViewModel.userConfigResult.value == null) {
if(isLogout){// 退出登录后,显示登录页 if(isLogout){// 退出登录后,显示登录页
// 同意隐私协议政策,检验是否有一键登录权限
loginViewModel.oneKeyLoginForGeTuiSdk(context as Activity) { isAllowShowOneKeyScreen ->
if (isAllowShowOneKeyScreen) {
loginViewModel.loginScreenType.value = LoginScreenType.LOGIN_ONE_KEY
} else {
// 检验是否有一键登录权限失败,显示验证码登录
loginViewModel.loginScreenType.value = LoginScreenType.LOGIN_CAPTCHA
}
}
// 显示登录页 // 显示登录页
LoginScreen(generalViewModel = generalViewModel, loginViewModel = loginViewModel, isVisibilityBreak = false) LoginScreen(generalViewModel = generalViewModel, loginViewModel = loginViewModel, isVisibilityBreak = false)
} else { } else {
@ -352,8 +337,8 @@ class MainActivity : ComponentActivity(), LoadingCallback {
} }
//UniApp更新提示 //UniApp更新提示
val isDownloadingWGT = mutableStateOf(false) val isDownloadingWGT = remember(showUniUpdateDialog) { mutableStateOf(false) }
val progressWGTState = mutableFloatStateOf(0f) val progressWGTState = remember(showUniUpdateDialog) { mutableFloatStateOf(0f) }
if(showUniUpdateDialog){ if(showUniUpdateDialog){
updateUniEntity?.let { updateUniEntity?.let {
TipsUniMpDialog( TipsUniMpDialog(
@ -366,11 +351,17 @@ class MainActivity : ComponentActivity(), LoadingCallback {
data = it, data = it,
isStartDown = isDownloadingWGT, isStartDown = isDownloadingWGT,
downProgress = progressWGTState, downProgress = progressWGTState,
reportViewModel = reportViewModel,
pagePath = updateUniPagePath,
onStatusChange = { isUpdateFinish, isCancel, data -> onStatusChange = { isUpdateFinish, isCancel, data ->
if(!isUpdateFinish && !isCancel && data != null){ if(!isUpdateFinish && !isCancel && data != null){
isDownloadingWGT.value = true isDownloadingWGT.value = true
}else{ }else{
showUniUpdateDialog = false showUniUpdateDialog = false
if (isCancel) {
UniAppUtils.reportUpdateChoice(it, false, reportViewModel)
UniAppUtils.distributeUniMp(context, it, reportViewModel, updateUniPagePath) {}
}
} }
} }
) )
@ -739,4 +730,4 @@ fun MainScreenPreview() {
AppTheme { AppTheme {
MainScreen(generalViewModel = viewModel(), loginViewModel = viewModel()) MainScreen(generalViewModel = viewModel(), loginViewModel = viewModel())
} }
} }

View File

@ -1,14 +1,17 @@
package com.img.rabbit.bean.request package com.img.rabbit.bean.request
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
@Serializable @Serializable
@OptIn(ExperimentalSerializationApi::class)
data class ReportRequest( data class ReportRequest(
private val source: String = "android",
private val type: String,//事件类型:click error private val type: String,//事件类型:click error
private val key: String, private val key: String,
private val value: String, private val value: String,
private val extra: String? = null private val extra: String? = null,
@EncodeDefault private val source: String = "android"
) )
@ -18,6 +21,13 @@ object ReportType {
} }
object ReportKey { object ReportKey {
const val EVENT_CLIENT_OPEN_WX_UNIMP = "event_client_open_wx_unimp"
const val EVENT_CLIENT_OPEN_ALIPAY_UNIMP = "event_client_open_alipay_unimp"
const val EVENT_CLIENT_UNI_FAIL = "client.uni.fail"
const val EVENT_CLIENT_DOWNLOAD_UNIMP_ERROR = "client.download.unimp.error"
const val EVENT_CLIENT_DOWNLOAD_UNIMP_SUCCESS = "client.download.unimp.success"
const val EVENT_CLIENT_CANCEL_DOWNLOAD_UNIMP = "client.cancel.download.unimp"
const val EVENT_CLIENT_CONFIRM_DOWNLOAD_UNIMP = "client.confirm.download.unimp"
const val EVENT_CLIENT_UNI_RELEASE_WGT: String = "client.uni.release.wgt" //释放资源 const val EVENT_CLIENT_UNI_RELEASE_WGT: String = "client.uni.release.wgt" //释放资源
const val EVENT_CLIENT_UNI_SPEC_PAGE_LOAD: String = "client.uni.page.load" //页面加载 const val EVENT_CLIENT_UNI_SPEC_PAGE_LOAD: String = "client.uni.page.load" //页面加载
} }

View File

@ -13,6 +13,8 @@ class ConfigEntity {
var homeIconEntity: List<UniIconEntity>? = emptyList() var homeIconEntity: List<UniIconEntity>? = emptyList()
@SerializedName("client.wgt.password") //WGT解压密码 @SerializedName("client.wgt.password") //WGT解压密码
var wgtPassword: String? = null var wgtPassword: String? = null
@SerializedName("client.uni.pwd") //与 WGT 密码后缀拼接的小程序密码
var uniPassword: String? = null
@SerializedName("client.uni.open") //是否开启小程序模拟器 @SerializedName("client.uni.open") //是否开启小程序模拟器
var isUniMpOpen: Boolean? = null var isUniMpOpen: Boolean? = null
@ -40,4 +42,4 @@ class ConfigEntity {
@SerializedName("client.login.type") //登录方式 @SerializedName("client.login.type") //登录方式
var loginType: List<String>? = emptyList() var loginType: List<String>? = emptyList()
} }

View File

@ -14,4 +14,5 @@ class UniVersionEntity(
var unimp_id: String = "", var unimp_id: String = "",
var unimp_type: String = "", var unimp_type: String = "",
var icon: String = "", var icon: String = "",
) var urls: List<String>? = emptyList(),
)

View File

@ -32,6 +32,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.ClickableText import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.Checkbox import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
@ -92,6 +93,19 @@ import org.json.JSONObject
fun LoginScreen(navController: NavHostController? = null, generalViewModel: GeneralViewModel, loginViewModel: LoginViewModel, isVisibilityBreak: Boolean) { fun LoginScreen(navController: NavHostController? = null, generalViewModel: GeneralViewModel, loginViewModel: LoginViewModel, isVisibilityBreak: Boolean) {
val TAG = "Rabbit_LoginScreen" val TAG = "Rabbit_LoginScreen"
val context = LocalContext.current val context = LocalContext.current
var isPreparingOneKeyLogin by remember(loginViewModel) { mutableStateOf(true) }
LaunchedEffect(loginViewModel) {
loginViewModel.setIsPolicyAgreement(false)
val activity = context as? Activity
val available = activity != null && loginViewModel.prepareOneKeyLogin(activity)
loginViewModel.loginScreenType.value = if (available) {
LoginScreenType.LOGIN_ONE_KEY
} else {
LoginScreenType.LOGIN_CAPTCHA
}
isPreparingOneKeyLogin = false
}
//关于登录的事件监听 //关于登录的事件监听
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
@ -150,39 +164,48 @@ fun LoginScreen(navController: NavHostController? = null, generalViewModel: Gene
.fillMaxSize() .fillMaxSize()
) { ) {
Box(modifier = Modifier.fillMaxSize()){ Box(modifier = Modifier.fillMaxSize()){
loginViewModel.setIsPolicyAgreement(false) if (isPreparingOneKeyLogin) {
when(loginViewModel.loginScreenType.value){ Column(
LoginScreenType.LOGIN_ONE_KEY -> { modifier = Modifier.align(Alignment.Center),
//一键登录 horizontalAlignment = Alignment.CenterHorizontally
OneKeyLoginScreen(context, loginViewModel) ) {
CircularProgressIndicator()
Text("正在获取本机号码…", modifier = Modifier.padding(top = 16.dp))
} }
LoginScreenType.LOGIN_WX -> { } else {
//微信登录 when(loginViewModel.loginScreenType.value){
Box(modifier = Modifier.align(Alignment.Center).padding(bottom = 100.dp)){ LoginScreenType.LOGIN_ONE_KEY -> {
WxLoginScreen(context, loginViewModel, generalViewModel) //一键登录
OneKeyLoginScreen(context, loginViewModel)
} }
LoginScreenType.LOGIN_WX -> {
//微信登录
Box(modifier = Modifier.align(Alignment.Center).padding(bottom = 100.dp)){
WxLoginScreen(context, loginViewModel, generalViewModel)
}
} }
LoginScreenType.LOGIN_ALIPAY -> { LoginScreenType.LOGIN_ALIPAY -> {
//支付宝登录 //支付宝登录
Box(modifier = Modifier.align(Alignment.Center).padding(bottom = 100.dp)){ Box(modifier = Modifier.align(Alignment.Center).padding(bottom = 100.dp)){
AliPayLoginScreen(context, loginViewModel) AliPayLoginScreen(context, loginViewModel)
}
}
else -> {
//默认验证码登录
CaptchaLoginScreen(context, loginViewModel)
} }
} }
else -> {
//默认验证码登录
CaptchaLoginScreen(context, loginViewModel)
}
}
// 其他登录方式Bar // 其他登录方式Bar
Column ( Column (
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(top = 27.dp), .padding(top = 27.dp),
verticalArrangement = Arrangement.Bottom verticalArrangement = Arrangement.Bottom
){ ){
OtherLoginBar(viewModel = loginViewModel) OtherLoginBar(viewModel = loginViewModel)
}
} }
} }
} }
@ -316,7 +339,11 @@ private fun CaptchaLoginScreen(context: Context, viewModel: LoginViewModel) {
BasicTextField( BasicTextField(
value = viewModel.userName.value, value = viewModel.userName.value,
onValueChange = { viewModel.setUserName(it) }, onValueChange = {
if (it.length <= 11) {
viewModel.setUserName(it)
}
},
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.background(Color.Transparent) .background(Color.Transparent)
@ -391,7 +418,7 @@ private fun CaptchaLoginScreen(context: Context, viewModel: LoginViewModel) {
singleLine = true, singleLine = true,
maxLines = 1, maxLines = 1,
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = androidx.compose.ui.text.input.KeyboardType.Text, keyboardType = androidx.compose.ui.text.input.KeyboardType.Number,
imeAction = androidx.compose.ui.text.input.ImeAction.Done imeAction = androidx.compose.ui.text.input.ImeAction.Done
), ),
decorationBox = { innerTextField -> decorationBox = { innerTextField ->
@ -599,24 +626,18 @@ private fun CaptchaLoginScreen(context: Context, viewModel: LoginViewModel) {
@SuppressLint("UseKtx", "InflateParams", "SetTextI18n") @SuppressLint("UseKtx", "InflateParams", "SetTextI18n")
@Composable @Composable
private fun OneKeyLoginScreen(context: Context, viewModel: LoginViewModel) { private fun OneKeyLoginScreen(context: Context, viewModel: LoginViewModel) {
val TAG = "Rabbit_LoginScreen_OneKeyLoginScreen"
val preLoginResult = GYManager.getInstance().preLoginResult val preLoginResult = GYManager.getInstance().preLoginResult
val phoneNumber = viewModel.oneKeyPreLogin?.number ?: "" if (preLoginResult == null || !preLoginResult.isValid) {
val operator = preLoginResult.operator//运营商,CM 移动,CT 电信,CU 联通 LaunchedEffect(Unit) {
viewModel.loginScreenType.value = LoginScreenType.LOGIN_CAPTCHA
}
return
}
val phoneNumber = viewModel.oneKeyPreLogin?.number.orEmpty()
val operator = preLoginResult.operator
val privacyName = "《${preLoginResult.privacyName}》" val privacyName = "《${preLoginResult.privacyName}》"
val privacyUrl = preLoginResult.privacyUrl val privacyUrl = preLoginResult.privacyUrl
// 详细打印preLoginResult信息
Log.w(TAG, "=== preLoginResult 详细信息 ===")
Log.w(TAG, "preLoginResult对象: $preLoginResult")
Log.w(TAG, "operator: ${preLoginResult.operator}")
Log.w(TAG, "isValid: ${preLoginResult.isValid}")
Log.w(TAG, "privacyName: ${preLoginResult.privacyName}")
Log.w(TAG, "privacyUrl: ${preLoginResult.privacyUrl}")
Log.w(TAG, "================================")
val agreementText = "登录即认可${privacyName}、《用户协议》和《隐私政策》并使用本机号码登录" val agreementText = "登录即认可${privacyName}、《用户协议》和《隐私政策》并使用本机号码登录"
Column( Column(
modifier = Modifier modifier = Modifier
@ -626,15 +647,12 @@ private fun OneKeyLoginScreen(context: Context, viewModel: LoginViewModel) {
// 使用AndroidView嵌入XML布局 // 使用AndroidView嵌入XML布局
@Suppress("COMPOSE_APPLIER_CALL_MISMATCH") @Suppress("COMPOSE_APPLIER_CALL_MISMATCH")
AndroidView( AndroidView(
factory = { context -> factory = { viewContext ->
LayoutInflater.from(context).inflate( val view = LayoutInflater.from(viewContext).inflate(
R.layout.layout_one_key_login, R.layout.layout_one_key_login,
null, null,
false false
) as ConstraintLayout ) as ConstraintLayout
},
modifier = Modifier.fillMaxSize(),
update = { view ->
// 动态更新XML布局中的内容 // 动态更新XML布局中的内容
val phoneTextView = view.findViewById<TextView>(R.id.layout_one_key_login_tv_phone) val phoneTextView = view.findViewById<TextView>(R.id.layout_one_key_login_tv_phone)
phoneTextView.text = phoneNumber // 需要回去手机号码 phoneTextView.text = phoneNumber // 需要回去手机号码
@ -686,18 +704,17 @@ private fun OneKeyLoginScreen(context: Context, viewModel: LoginViewModel) {
privacyTv = agreementTextView, privacyTv = agreementTextView,
viewModel = viewModel viewModel = viewModel
) )
// loginButton.setOnClickListener { view
// // 处理登录点击 },
// oneKeyLogin( modifier = Modifier.fillMaxSize(),
// context = context, update = { view ->
// numberTv = phoneTextView, // 只更新勾选状态,避免重绘时重复注册 SDK 登录回调。
// sloganTv = serviceTextView, val checkbox = view.findViewById<CheckBox>(R.id.layout_one_key_login_agreement_checkbox)
// loginBtn = loginButton, checkbox.setOnCheckedChangeListener(null)
// checkBox = checkbox, checkbox.isChecked = viewModel.isPolicyAgreement.value
// privacyTv = agreementTextView, checkbox.setOnCheckedChangeListener { _, isChecked ->
// viewModel = viewModel viewModel.setIsPolicyAgreement(isChecked)
// ) }
// }
} }
) )
} }
@ -1187,36 +1204,58 @@ private fun oneKeyLogin(
privacyTv: TextView, privacyTv: TextView,
viewModel: LoginViewModel, viewModel: LoginViewModel,
) { ) {
val activity = context as Activity
fun fallbackToCaptcha() {
activity.runOnUiThread {
loginBtn.isEnabled = true
if (viewModel.loginScreenType.value == LoginScreenType.LOGIN_ONE_KEY) {
viewModel.loginScreenType.value = LoginScreenType.LOGIN_CAPTCHA
CenterToast.show("一键登录暂不可用,请使用验证码登录")
}
}
}
val gyCallBack = object : GyCallBack { val gyCallBack = object : GyCallBack {
override fun onSuccess(response: GYResponse?) { override fun onSuccess(response: GYResponse?) {
loginBtn.isEnabled = true activity.runOnUiThread {
Log.i("OneKeyLogin", "OneKeyLoginViewModel------onSuccess:$response") loginBtn.isEnabled = true
try { if (viewModel.loginScreenType.value != LoginScreenType.LOGIN_ONE_KEY) return@runOnUiThread
val jsonObject = JSONObject(response?.msg?:"{}") try {
val data = jsonObject.getJSONObject("data") val data = JSONObject(response?.msg ?: "{}").getJSONObject("data")
val token = data.getString("token") val token = data.getString("token")
viewModel.requestOneKeyLogin(response?.gyuid?:"", token) val gyuid = response?.gyuid.orEmpty()
} catch (e: Exception) { if (token.isBlank() || gyuid.isBlank()) {
e.printStackTrace() fallbackToCaptcha()
} else {
viewModel.requestOneKeyLogin(gyuid, token)
}
} catch (e: Exception) {
Log.w("OneKeyLogin", "一键登录凭证解析失败", e)
fallbackToCaptcha()
}
} }
} }
override fun onFailed(p0: GYResponse?) { override fun onFailed(p0: GYResponse?) {
loginBtn.isEnabled = true fallbackToCaptcha()
Log.e("OneKeyLogin", "OneKeyLoginViewModel------onFailed:$p0")
} }
} }
val eloginActivityParam = EloginActivityParam() val eloginActivityParam = EloginActivityParam()
.setActivity(context as Activity) .setActivity(activity)
.setNumberTextview(numberTv) .setNumberTextview(numberTv)
.setSloganTextview(sloganTv) .setSloganTextview(sloganTv)
.setLoginButton(loginBtn) .setLoginButton(loginBtn)
.setPrivacyCheckbox(checkBox) .setPrivacyCheckbox(checkBox)
.setPrivacyTextview(privacyTv) .setPrivacyTextview(privacyTv)
.setUiErrorListener { msg -> .setUiErrorListener { msg ->
loginBtn.isEnabled = true activity.runOnUiThread {
Log.e("OneKeyLogin", "OneKeyLoginViewModel------UIErrorListener.onError:$msg") loginBtn.isEnabled = true
if (checkBox.isChecked) {
fallbackToCaptcha()
} else {
CenterToast.show("请先同意用户协议和隐私政策")
}
}
} }
.setLoginOnClickListener { .setLoginOnClickListener {
if (!checkBox.isChecked) { if (!checkBox.isChecked) {
@ -1226,7 +1265,12 @@ private fun oneKeyLogin(
} }
// 预先注册登录回调 // 预先注册登录回调
GYManager.getInstance().eAccountLogin(eloginActivityParam, 5000, gyCallBack) try {
GYManager.getInstance().eAccountLogin(eloginActivityParam, 5000, gyCallBack)
} catch (e: Exception) {
Log.w("OneKeyLogin", "一键登录授权页初始化失败", e)
fallbackToCaptcha()
}
} }
enum class LoginScreenType { enum class LoginScreenType {

View File

@ -58,9 +58,31 @@ import com.img.rabbit.viewmodel.LoginViewModel
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
// 定义底部导航的标签页 // 定义底部导航的标签页
sealed class TabItem(val title: String, val router:String, val normalIconRes: Int, val selectedIconRes: Int, val normalColor: Color, val selectedColor: Color) { sealed class TabItem(
object Home : TabItem("首页", "home", R.mipmap.ic_home_normal, R.mipmap.ic_home_selected, Color(0xFFAAAAAA), Color(0xFF1A1A1A)) val title: String,
object Mine : TabItem("我的", "mine", R.mipmap.ic_mine_normal, R.mipmap.ic_mine_selected, Color(0xFFAAAAAA), Color(0xFF1A1A1A)) val router: String,
val normalIconRes: Int,
val selectedIconRes: Int,
val normalColor: Color,
val selectedColor: Color
) {
object Home : TabItem(
"首页",
"home",
R.mipmap.ic_home_normal,
R.mipmap.ic_home_selected,
Color(0xFFAAAAAA),
Color(0xFF1A1A1A)
)
object Mine : TabItem(
"我的",
"mine",
R.mipmap.ic_mine_normal,
R.mipmap.ic_mine_selected,
Color(0xFFAAAAAA),
Color(0xFF1A1A1A)
)
} }
/** /**
@ -72,7 +94,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
val navController = rememberNavController() val navController = rememberNavController()
val networkStatus by generalViewModel.networkStatus.observeAsState(initial = true) val networkStatus by generalViewModel.networkStatus.observeAsState(initial = true)
val isNavigationBarVisible by generalViewModel.isNavigationBarVisible.observeAsState(initial = true) val isNavigationBarVisible by generalViewModel.isNavigationBarVisible.observeAsState(initial = true)
val tabItems = listOf( TabItem.Home, TabItem.Mine ) val tabItems = listOf(TabItem.Home, TabItem.Mine)
var selectedTab: TabItem by remember { mutableStateOf(TabItem.Home) } var selectedTab: TabItem by remember { mutableStateOf(TabItem.Home) }
generalViewModel.navController = navController generalViewModel.navController = navController
@ -84,7 +106,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
selectedTab = TabItem.Home selectedTab = TabItem.Home
// 显示TabBar // 显示TabBar
generalViewModel.setNavigationBarVisible(true) generalViewModel.setNavigationBarVisible(true)
}else if(navBackStackEntry?.destination?.route == "mine"){ } else if (navBackStackEntry?.destination?.route == "mine") {
selectedTab = TabItem.Mine selectedTab = TabItem.Mine
// 显示TabBar // 显示TabBar
generalViewModel.setNavigationBarVisible(true) generalViewModel.setNavigationBarVisible(true)
@ -95,7 +117,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
LaunchedEffect(networkStatus) { LaunchedEffect(networkStatus) {
if (!networkStatus) { if (!networkStatus) {
// 网络断开时的处理 // 网络断开时的处理
Log.w("NetworkStatus","网络断开") Log.w("NetworkStatus", "网络断开")
//延迟500ms,确保页面初始化完成后,再跳转网络错误页面 //延迟500ms,确保页面初始化完成后,再跳转网络错误页面
delay(500) delay(500)
@ -104,13 +126,13 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
navController.navigate("netError") navController.navigate("netError")
generalViewModel.setNavigationBarVisible(false) generalViewModel.setNavigationBarVisible(false)
*/ */
}else{ } else {
/* /*
if(navBackStackEntry?.destination?.route == "home"||navBackStackEntry?.destination?.route == "mine"){ if(navBackStackEntry?.destination?.route == "home"||navBackStackEntry?.destination?.route == "mine"){
generalViewModel.setNavigationBarVisible(true) generalViewModel.setNavigationBarVisible(true)
} }
*/ */
Log.w("NetworkStatus","网络已连接") Log.w("NetworkStatus", "网络已连接")
} }
} }
@ -122,7 +144,11 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
) { ) {
Box(modifier = Modifier.height(52.dp)) { Box(modifier = Modifier.height(52.dp)) {
NavigationBar( NavigationBar(
containerColor = Color.White, containerColor = if (selectedTab == TabItem.Mine) {
Color(0xFFF9F9F9)
} else {
Color.White
},
contentColor = Color.Transparent contentColor = Color.Transparent
) { ) {
tabItems.forEachIndexed { index, item -> tabItems.forEachIndexed { index, item ->
@ -140,12 +166,17 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
modifier = Modifier.clickable( modifier = Modifier.clickable(
interactionSource = remember { MutableInteractionSource() }, interactionSource = remember { MutableInteractionSource() },
indication = null indication = null
){ ) {
selectedTab = tabItems[index] selectedTab = tabItems[index]
} }
) )
}, },
label = { Text(item.title, color = if (selectedTab == tabItems[index]) item.selectedColor else item.normalColor) }, label = {
Text(
item.title,
color = if (selectedTab == tabItems[index]) item.selectedColor else item.normalColor
)
},
selected = selectedTab == tabItems[index], selected = selectedTab == tabItems[index],
onClick = { selectedTab = tabItems[index] }, onClick = { selectedTab = tabItems[index] },
interactionSource = remember { MutableInteractionSource() }, interactionSource = remember { MutableInteractionSource() },
@ -255,15 +286,17 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
} }
) )
) { backStackEntry -> ) { backStackEntry ->
val isVisibilityBreak = when(backStackEntry.arguments?.getInt("type")){ val isVisibilityBreak = when (backStackEntry.arguments?.getInt("type")) {
LoginViewModel.JumpLoginType.FROM_ADD.type -> { LoginViewModel.JumpLoginType.FROM_ADD.type -> {
// 添加账号 // 添加账号
true true
} }
LoginViewModel.JumpLoginType.FROM_LOGOUT.type -> { LoginViewModel.JumpLoginType.FROM_LOGOUT.type -> {
// 退出登录 // 退出登录
false false
} }
else -> false else -> false
} }
LoginScreen( LoginScreen(
@ -296,7 +329,8 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
BindScreen( BindScreen(
navController = navController, navController = navController,
generalViewModel = generalViewModel, generalViewModel = generalViewModel,
bindType = backStackEntry.arguments?.getInt("type")?:BindViewModel.BindType.FROM_PHONE.type bindType = backStackEntry.arguments?.getInt("type")
?: BindViewModel.BindType.FROM_PHONE.type
) )
} }
@ -305,7 +339,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
NetworkDisconnectedPage( NetworkDisconnectedPage(
navController = navController, navController = navController,
generalViewModel = generalViewModel, generalViewModel = generalViewModel,
){ ) {
} }
} }
@ -317,6 +351,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
TabItem.Home -> navController.navigate(ScreenRoute.Home.route) { TabItem.Home -> navController.navigate(ScreenRoute.Home.route) {
popUpTo(ScreenRoute.Home.route) { inclusive = true } popUpTo(ScreenRoute.Home.route) { inclusive = true }
} }
TabItem.Mine -> navController.navigate(ScreenRoute.Mine.route) { TabItem.Mine -> navController.navigate(ScreenRoute.Mine.route) {
popUpTo(ScreenRoute.Mine.route) { inclusive = true } popUpTo(ScreenRoute.Mine.route) { inclusive = true }
} }

View File

@ -37,6 +37,7 @@ import com.img.rabbit.R
import com.img.rabbit.bean.response.UniVersionEntity import com.img.rabbit.bean.response.UniVersionEntity
import com.img.rabbit.utils.UniAppUtils import com.img.rabbit.utils.UniAppUtils
import com.img.rabbit.utils.UniMpUpdate import com.img.rabbit.utils.UniMpUpdate
import com.img.rabbit.viewmodel.ReportViewModel
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
@Composable @Composable
@ -50,6 +51,8 @@ fun TipsUniMpDialog(
data: UniVersionEntity, data: UniVersionEntity,
isStartDown: MutableState<Boolean>, isStartDown: MutableState<Boolean>,
downProgress: MutableState<Float>, downProgress: MutableState<Float>,
reportViewModel: ReportViewModel,
pagePath: String?,
onStatusChange: (state: Boolean, isCancel:Boolean, data: Any?) -> Unit onStatusChange: (state: Boolean, isCancel:Boolean, data: Any?) -> Unit
){ ){
val context = LocalContext.current val context = LocalContext.current
@ -61,7 +64,7 @@ fun TipsUniMpDialog(
indication = null, indication = null,
interactionSource = remember { MutableInteractionSource() } interactionSource = remember { MutableInteractionSource() }
) { ) {
onStatusChange(false, true, data) if (!isStartDown.value) onStatusChange(false, true, data)
}, },
verticalArrangement = Arrangement.Center verticalArrangement = Arrangement.Center
){ ){
@ -213,7 +216,8 @@ fun TipsUniMpDialog(
interactionSource = remember { MutableInteractionSource() } interactionSource = remember { MutableInteractionSource() }
) { ) {
onStatusChange(false, false, data) onStatusChange(false, false, data)
UniAppUtils.downloadWGT(context, scope, data){ uniState, filePath, progress -> UniAppUtils.reportUpdateChoice(data, true, reportViewModel)
UniAppUtils.downloadWGT(context, scope, data, reportViewModel, pagePath){ uniState, _, progress ->
when (uniState) { when (uniState) {
UniMpUpdate.DOWNLOAD_START -> { UniMpUpdate.DOWNLOAD_START -> {
//资源开始下载 //资源开始下载
@ -229,6 +233,7 @@ fun TipsUniMpDialog(
UniMpUpdate.DOWNLOAD_FAIL -> { UniMpUpdate.DOWNLOAD_FAIL -> {
//资源下载失败 //资源下载失败
downProgress.value = -1f downProgress.value = -1f
onStatusChange(true, false, data)
Log.i("HomeScreen","DOWNLOAD_FAIL") Log.i("HomeScreen","DOWNLOAD_FAIL")
} }
else -> { else -> {
@ -261,4 +266,4 @@ fun TipsUniMpDialog(
} }
} }
} }

View File

@ -269,7 +269,7 @@ fun HomeScreen(
) )
//下载完成前显示 //下载完成前显示
if((progressPair[uniMpId]?:0f) > 0f && (progressPair[uniMpId]?:0f) < 1f){ if((progressPair[uniMpId]?:-1f) >= 0f && (progressPair[uniMpId]?:-1f) < 1f){
Box( Box(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@ -343,7 +343,7 @@ fun HomeScreen(
) )
//下载完成前显示 //下载完成前显示
if((progressPair[uniMpId]?:0f) > 0f && (progressPair[uniMpId]?:0f) < 1f){ if((progressPair[uniMpId]?:-1f) >= 0f && (progressPair[uniMpId]?:-1f) < 1f){
Box( Box(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@ -411,18 +411,11 @@ fun HomeScreen(
CenterToast.show("无可用资源...") CenterToast.show("无可用资源...")
return@clickable return@clickable
} }
val uniMpId = uniVersion.unimp_id dealUniMpDownloadLaunch(
UniAppUtils.currentUniMpJumpPatch = item.url context, scope, uniVersion, progressPair,
val wgtExists = UniAppUtils.wgtIsExists(uniMpId) reportViewModel, loadingCallback,
if(!wgtExists){ pagePath = item.url, itemName = item.text
//是否下载 )
scope.launch {
GlobalEventBus.emit(
GlobalEvent.ShowUniDownloadNotify(uniVersion))
}
}else {
UniAppUtils.startUniMpPage(context = context, uniMpId = uniMpId, uniMpType = item.type, pagePath = item.url, reportViewModel = reportViewModel)
}
} }
) { ) {
Column { Column {
@ -765,17 +758,32 @@ private fun dealUniMpDownloadLaunch(
uniMp: UniVersionEntity, uniMp: UniVersionEntity,
progressPair: SnapshotStateMap<String, Float>, progressPair: SnapshotStateMap<String, Float>,
reportViewModel: ReportViewModel, reportViewModel: ReportViewModel,
loadingCallback: LoadingCallback?){ loadingCallback: LoadingCallback?,
pagePath: String? = null,
itemName: String = "",
){
val TAG = "Rabbit_HomeScreen_download" val TAG = "Rabbit_HomeScreen_download"
val uniMpId = uniMp.unimp_id val uniMpId = uniMp.unimp_id
UniAppUtils.reportOpen(uniMp, itemName.ifEmpty { if (uniMp.unimp_type == "wx") "微信模拟器" else "小宝模拟器" }, reportViewModel)
if (UniAppUtils.isBusy(uniMpId)) {
CenterToast.show("请等待模拟器更新完毕!")
return
}
if (UniAppUtils.showRunningUniMp(uniMpId, pagePath)) return
// 处理点击事件,微信模拟器 // 处理点击事件,微信模拟器
if (UniAppUtils.isDownloadUniMp(uniMp)) { if (UniAppUtils.isDownloadUniMp(uniMp)) {
if (pagePath != null) {
scope.launch { GlobalEventBus.emit(GlobalEvent.ShowUniDownloadNotify(uniMp, pagePath)) }
return
}
//没有下载或者强制更新(更新释放新版本并启动) //没有下载或者强制更新(更新释放新版本并启动)
UniAppUtils.downloadWGT( UniAppUtils.downloadWGT(
context, context,
scope, scope,
uniMp uniMp,
reportViewModel,
pagePath
) { uniState, _, progress -> ) { uniState, _, progress ->
progressPair[uniMpId] progressPair[uniMpId]
?: mutableMapOf<String, Float>().apply { put(uniMpId, 0f) } ?: mutableMapOf<String, Float>().apply { put(uniMpId, 0f) }
@ -818,15 +826,14 @@ private fun dealUniMpDownloadLaunch(
} }
} else if (UniAppUtils.isUpdate(uniMp)) { } else if (UniAppUtils.isUpdate(uniMp)) {
// 提示更新(1、更新释放新版本并启动;2、直接启动现有版本) // 提示更新(1、更新释放新版本并启动;2、直接启动现有版本)
UniAppUtils.currentUpdateUniMp = uniMp
scope.launch { scope.launch {
GlobalEventBus.emit( GlobalEventBus.emit(
GlobalEvent.ShowUniUpdateNotify(uniMp)) GlobalEvent.ShowUniUpdateNotify(uniMp, pagePath))
} }
} else { } else {
loadingCallback?.showLoading() loadingCallback?.showLoading()
//启动uni小程序(1、直接启动;2、释放并启动) //启动uni小程序(1、直接启动;2、释放并启动)
UniAppUtils.distributeUniMp(context, uniMp, reportViewModel) { UniAppUtils.distributeUniMp(context, uniMp, reportViewModel, pagePath) {
loadingCallback?.hideLoading() loadingCallback?.hideLoading()
} }
} }

View File

@ -11,21 +11,30 @@ import com.img.rabbit.R;
import io.dcloud.feature.sdk.Interface.IDCUniMPAppSplashView; import io.dcloud.feature.sdk.Interface.IDCUniMPAppSplashView;
public class UniMPAlipaySplashView implements IDCUniMPAppSplashView { public class UniMPAlipaySplashView implements IDCUniMPAppSplashView {
FrameLayout splashView; private FrameLayout splashView;
private UniMPSplashWindow splashWindow;
@Override @Override
public View getSplashView(Context context, String appid, String s1, String s2) { public View getSplashView(Context context, String appid, String s1, String s2) {
if (splashWindow != null) splashWindow.close();
splashView = new FrameLayout(context); splashView = new FrameLayout(context);
ImageView imageView = new ImageView(context); ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(R.mipmap.ic_launch_alipay_unimp); imageView.setImageResource(R.mipmap.ic_launch_alipay_unimp);
splashView.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); splashView.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
splashWindow = new UniMPSplashWindow(context, splashView, true);
return splashView; return splashView;
} }
@Override @Override
public void onCloseSplash(ViewGroup rootView) { public void onCloseSplash(ViewGroup rootView) {
if(rootView != null) if (splashWindow != null) {
splashWindow.close();
splashWindow = null;
}
if (rootView != null && splashView != null) {
rootView.removeView(splashView); rootView.removeView(splashView);
}
splashView = null;
} }
} }

View File

@ -0,0 +1,121 @@
package com.img.rabbit.uni
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Color
import android.os.Build
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import androidx.core.view.WindowCompat
/** 只在 UniMP 启动图显示期间让图片延伸到系统导航栏下方。 */
@Suppress("DEPRECATION")
class UniMPSplashWindow(
context: Context,
private val splashView: View,
private val darkNavigationIcons: Boolean,
) :
View.OnAttachStateChangeListener, ViewTreeObserver.OnGlobalLayoutListener {
private val window = findActivity(context)?.window
private val originalNavigationBarColor = window?.navigationBarColor
private val originalSystemUiVisibility = window?.decorView?.systemUiVisibility ?: 0
private val originalWindowFlags = window?.attributes?.flags ?: 0
private val originalDividerColor = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) window?.navigationBarDividerColor else null
private val originalContrastEnforced = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) window?.isNavigationBarContrastEnforced else null
private val insetsController = window?.let { WindowCompat.getInsetsController(it, it.decorView) }
private val originalLightNavigationBars = insetsController?.isAppearanceLightNavigationBars ?: false
private var observer: ViewTreeObserver? = null
private var closed = false
private val reapply = Runnable { applyTransparentNavigationBar() }
init {
splashView.addOnAttachStateChangeListener(this)
applyTransparentNavigationBar()
if (splashView.isAttachedToWindow) onViewAttachedToWindow(splashView)
}
override fun onViewAttachedToWindow(view: View) {
if (closed) return
observer?.takeIf { it.isAlive }?.removeOnGlobalLayoutListener(this)
observer = view.viewTreeObserver.also { it.addOnGlobalLayoutListener(this) }
applyTransparentNavigationBar()
// SDK 初始化窗口时可能覆盖导航栏配置,启动阶段短暂补设。
view.removeCallbacks(reapply)
for (attempt in 1..10) view.postDelayed(reapply, attempt * 50L)
}
override fun onGlobalLayout() = applyTransparentNavigationBar()
override fun onViewDetachedFromWindow(view: View) = close()
private fun applyTransparentNavigationBar() {
val window = window ?: return
if (closed) return
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
}
val decor = window.decorView
val visibility = decor.systemUiVisibility or LAYOUT_FLAGS
if (decor.systemUiVisibility != visibility) decor.systemUiVisibility = visibility
// 微信启动图为深色、支付宝为白色,分别使用浅色和深色导航按键。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && insetsController != null &&
insetsController.isAppearanceLightNavigationBars != darkNavigationIcons) {
insetsController.isAppearanceLightNavigationBars = darkNavigationIcons
}
}
fun close() {
if (closed) return
closed = true
// 先取消监听及延时任务,防止关闭后再次改动小程序正文的窗口。
splashView.removeCallbacks(reapply)
splashView.removeOnAttachStateChangeListener(this)
observer?.takeIf { it.isAlive }?.removeOnGlobalLayoutListener(this)
observer = null
val window = window ?: return
window.decorView.systemUiVisibility =
(window.decorView.systemUiVisibility and LAYOUT_FLAGS.inv()) or
(originalSystemUiVisibility and LAYOUT_FLAGS)
window.setFlags(originalWindowFlags and WINDOW_FLAGS, WINDOW_FLAGS)
originalNavigationBarColor?.let { window.navigationBarColor = it }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
originalDividerColor?.let { window.navigationBarDividerColor = it }
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
originalContrastEnforced?.let { window.isNavigationBarContrastEnforced = it }
}
insetsController?.isAppearanceLightNavigationBars = originalLightNavigationBars
}
private companion object {
const val LAYOUT_FLAGS = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
const val WINDOW_FLAGS = WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS or
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
fun findActivity(context: Context): Activity? {
var current = context
while (current is ContextWrapper) {
if (current is Activity) return current
val base = current.baseContext
if (base === current) break
current = base
}
return null
}
}
}

View File

@ -12,21 +12,30 @@ import com.img.rabbit.R;
import io.dcloud.feature.sdk.Interface.IDCUniMPAppSplashView; import io.dcloud.feature.sdk.Interface.IDCUniMPAppSplashView;
public class UniMPWxSplashView implements IDCUniMPAppSplashView { public class UniMPWxSplashView implements IDCUniMPAppSplashView {
FrameLayout splashView; private FrameLayout splashView;
private UniMPSplashWindow splashWindow;
@Override @Override
public View getSplashView(Context context, String appid, String s1, String s2) { public View getSplashView(Context context, String appid, String s1, String s2) {
if (splashWindow != null) splashWindow.close();
splashView = new FrameLayout(context); splashView = new FrameLayout(context);
ImageView imageView = new ImageView(context); ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(R.mipmap.ic_launch_wx_unimp); imageView.setImageResource(R.mipmap.ic_launch_wx_unimp);
splashView.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); splashView.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
splashWindow = new UniMPSplashWindow(context, splashView, false);
return splashView; return splashView;
} }
@Override @Override
public void onCloseSplash(ViewGroup rootView) { public void onCloseSplash(ViewGroup rootView) {
if(rootView != null) if (splashWindow != null) {
splashWindow.close();
splashWindow = null;
}
if (rootView != null && splashView != null) {
rootView.removeView(splashView); rootView.removeView(splashView);
}
splashView = null;
} }
} }

View File

@ -68,8 +68,8 @@ sealed class UniMpWXPayEvent {
sealed class GlobalEvent { sealed class GlobalEvent {
object ShowAppUpdateNotify : GlobalEvent() object ShowAppUpdateNotify : GlobalEvent()
object ShowLoginNotify : GlobalEvent() object ShowLoginNotify : GlobalEvent()
data class ShowUniDownloadNotify(val entity: UniVersionEntity) : GlobalEvent() data class ShowUniDownloadNotify(val entity: UniVersionEntity, val pagePath: String? = null) : GlobalEvent()
data class ShowUniUpdateNotify(val entity: UniVersionEntity) : GlobalEvent() data class ShowUniUpdateNotify(val entity: UniVersionEntity, val pagePath: String? = null) : GlobalEvent()
} }
object GlobalEventBus { object GlobalEventBus {

View File

@ -1,8 +1,9 @@
package com.img.rabbit.utils package com.img.rabbit.utils
import android.content.Context import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log import android.util.Log
import android.webkit.MimeTypeMap
import com.github.gzuliyujiang.oaid.DeviceIdentifier import com.github.gzuliyujiang.oaid.DeviceIdentifier
import com.img.rabbit.BuildConfig import com.img.rabbit.BuildConfig
import com.img.rabbit.bean.request.ReportKey import com.img.rabbit.bean.request.ReportKey
@ -23,404 +24,316 @@ import io.dcloud.feature.sdk.DCUniMPSDK
import io.dcloud.feature.sdk.Interface.IUniMP import io.dcloud.feature.sdk.Interface.IUniMP
import io.dcloud.feature.unimp.config.UniMPOpenConfiguration import io.dcloud.feature.unimp.config.UniMPOpenConfiguration
import io.dcloud.feature.unimp.config.UniMPReleaseConfiguration import io.dcloud.feature.unimp.config.UniMPReleaseConfiguration
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient import kotlinx.serialization.json.Json
import okhttp3.Request
import java.io.File import java.io.File
import kotlin.jvm.java import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
/** /** UniMP 的下载、解压、启动及事件上报入口。 */
* UniApp工具类
* 小程序运行路径:/data/user/0/com.img.rabbit/files/apps/(一般/data/data/com.img.rabbit/files/apps/)
*/
object UniAppUtils { object UniAppUtils {
private const val TAG = "UniAppUtils" private const val TAG = "UniAppUtils"
/** private val mainHandler = Handler(Looper.getMainLooper())
* 所有运行的UniMp小程序实体 private val releaseExecutor = Executors.newSingleThreadExecutor()
*/ private val downloader = UniMpDownloader()
private val downloading = ConcurrentHashMap.newKeySet<String>()
private val releasing = ConcurrentHashMap.newKeySet<String>()
private val _uniMpFlow = MutableStateFlow<Map<String?, IUniMP?>>(emptyMap()) private val _uniMpFlow = MutableStateFlow<Map<String?, IUniMP?>>(emptyMap())
val uniMpFlow = _uniMpFlow.asStateFlow() val uniMpFlow = _uniMpFlow.asStateFlow()
fun updateUniMp(id: String?, mp: IUniMP?) { fun updateUniMp(id: String?, mp: IUniMP?) {
val currentMap = _uniMpFlow.value.toMutableMap() _uniMpFlow.update { it + (id to mp) }
currentMap[id] = mp
_uniMpFlow.value = currentMap
} }
//当前正在更新的小程序 private fun getWgtFile(uniMpId: String): File {
var currentUpdateUniMp: UniVersionEntity? = null require(uniMpId.matches(Regex("[A-Za-z0-9_-]+"))) { "无效的小程序 ID" }
//仅当跳转指定小程序时,才需要跳转指定位置 val directory = FileUtils.instance?.cacheUniAppDir ?: File(checkNotNull(applicationContext).cacheDir, "uniApp")
var currentUniMpJumpPatch: String? = null return File(directory, "$uniMpId.wgt")
private fun getWgtName(uniMpId: String): String{
return String.format("%s.wgt", uniMpId)
//return String.format("%s.zip", uniMpId)
} }
private fun getWgtFile(uniMpId: String): File{ fun getCurrentUniMp(): IUniMP? = uniMpFlow.value.values.firstOrNull { it?.isRunning == true }
val wgtName = getWgtName(uniMpId)
return File(FileUtils.instance?.cacheUniAppDir?.absolutePath, wgtName)
}
/**
*获取当前前台运行的UniMp小程序实体
*/
fun getCurrentUniMp(): IUniMP?{
return uniMpFlow.value.filter { it.value?.isRunning == true }.values.firstOrNull()
//return uniMpPair.filter { it.value?.isRunning == true }.values.firstOrNull()
}
/**
* 是否存在更新
*/
fun isUpdate(uniVersion: UniVersionEntity): Boolean{
return checkUpdate(uniVersion, PreferenceUtil.getWgtVersion(uniVersion.unimp_id)?:"0.0.0")
}
/** fun isUpdate(uniVersion: UniVersionEntity): Boolean = UniMpPolicy.isNewer(
* 是否强制更新 uniVersion.version, PreferenceUtil.getWgtVersion(uniVersion.unimp_id) ?: "0.0.0"
*/ )
private fun isUpdateForce(uniVersion: UniVersionEntity): Boolean{
return checkUpdate(uniVersion, PreferenceUtil.getWgtVersion(uniVersion.unimp_id)?:"0.0.0") && uniVersion.force
}
/** fun isDownloadUniMp(uniVersion: UniVersionEntity): Boolean =
* 是否需要下载(强制更新或者不存在wgt文件) UniMpPolicy.requiresDownload(uniVersion.force, wgtIsExists(uniVersion.unimp_id))
*/
fun isDownloadUniMp(uniVersion: UniVersionEntity): Boolean{
val wgtFile = getWgtFile(uniVersion.unimp_id)
return isUpdateForce(uniVersion) || !(FileUtils.instance?.fileIsExists(wgtFile) == true && FileUtils.getFileSize(wgtFile) > 0)
}
fun wgtIsExists(uniMpId: String): Boolean{ fun wgtIsExists(uniMpId: String): Boolean = runCatching {
val wgtFile = getWgtFile(uniMpId) getWgtFile(uniMpId).let { it.isFile && it.length() > 0 }
//判断wgt是否下载 }.getOrDefault(false)
return FileUtils.instance?.fileIsExists(wgtFile) == true && FileUtils.getFileSize(wgtFile) > 0
}
fun isRelease(uniMpId: String): Boolean{ fun isRelease(uniMpId: String): Boolean = DCUniMPSDK.getInstance().isExistsApp(uniMpId)
return DCUniMPSDK.getInstance().isExistsApp(uniMpId)
}
/** fun isBusy(uniMpId: String): Boolean = uniMpId in downloading || uniMpId in releasing
* 检查更新
*/
private fun checkUpdate(uniVersion: UniVersionEntity, currentVersion: String): Boolean {
val version = uniVersion.version
if(version.isEmpty())return false
val newVersions = version.split(".") /** 已运行的小程序直接显示,通过 jump 事件跳转,避免再次 openUniMP。 */
val originVersions = currentVersion.split(".") fun showRunningUniMp(uniMpId: String, pagePath: String?): Boolean {
if (isBusy(uniMpId)) return false
if(newVersions.size != 3 || originVersions.size != 3)return false return try {
val mp = _uniMpFlow.value[uniMpId] ?: return false
for (i in 0..2) { if ((mp.isRuning || mp.isRunning) && mp.showUniMP()) {
val newVal = newVersions[i].toIntOrNull() ?: 0 mp.sendUniMPEvent("jump", pagePath)
val oldVal = originVersions[i].toIntOrNull() ?: 0 true
} else false
if (newVal > oldVal) { } catch (e: Exception) {
return true Log.w(TAG, "恢复小程序失败,将重新启动: $uniMpId", e)
} else if (newVal < oldVal) { updateUniMp(uniMpId, null)
return false false
}
}
return false
}
/**
* 分发uniMP(下载、更新与启动)
*/
fun distributeUniMp(context: Context, uniVersion: UniVersionEntity,reportViewModel: ReportViewModel, onResult:(loading: Boolean) -> Unit){
val isExists = DCUniMPSDK.getInstance().isExistsApp(uniVersion.unimp_id)
if(isExists){
//资源已释放,直接启动
startUniMp(context, uniVersion, onResult)
}else{
//资源未释放,先释放后启动
releaseWgt(uniVersion,reportViewModel){ isSuccess, versionEntity ->
if(isSuccess){
startUniMp(context, versionEntity, onResult)
}else{
onResult(false)
}
}
} }
} }
private fun startUniMp(context: Context, uniVersion: UniVersionEntity, onResult:(loading: Boolean) -> Unit){ fun reportOpen(version: UniVersionEntity, itemName: String, reportViewModel: ReportViewModel) {
val uniMp = _uniMpFlow.value[uniVersion.unimp_id]//uniMpPair[uniVersion.unimp_id] report(reportViewModel, ReportType.CLICK,
if(uniMp?.isRuning == true){ if (version.unimp_type == "wx") ReportKey.EVENT_CLIENT_OPEN_WX_UNIMP else ReportKey.EVENT_CLIENT_OPEN_ALIPAY_UNIMP,
uniMp.showUniMP() itemName, "")
}else{
val configuration = getUniMPOpenConfiguration()
if(uniVersion.unimp_type == "wx"){
configuration.splashClass = UniMPWxSplashView::class.java
}else if("alipay" == uniVersion.unimp_type){
configuration.splashClass = UniMPAlipaySplashView::class.java
}
updateUniMp(uniVersion.unimp_id, DCUniMPSDK.getInstance().openUniMP(context, uniVersion.unimp_id, configuration))
}
onResult(false)
} }
/** fun reportUpdateChoice(version: UniVersionEntity, confirmed: Boolean, reportViewModel: ReportViewModel) {
* 启动小程序并直达指定页面 report(reportViewModel, ReportType.CLICK,
*/ if (confirmed) ReportKey.EVENT_CLIENT_CONFIRM_DOWNLOAD_UNIMP else ReportKey.EVENT_CLIENT_CANCEL_DOWNLOAD_UNIMP,
fun startUniMpPage(context: Context, uniMpId: String, uniMpType: String, pagePath: String, reportViewModel: ReportViewModel){ "", Json.encodeToString(version))
if(!isRelease(uniMpId)){
releaseWgt(uniMpId,reportViewModel){
if(it){
// 启动直达页面
startUniMpToPage(context, uniMpId, uniMpType, pagePath)
}
}
}else {
val uniMp = _uniMpFlow.value[uniMpId]
if(uniMp?.isRuning == true){
uniMp.showUniMP()
}
// 启动直达页面
startUniMpToPage(context, uniMpId, uniMpType, pagePath)
}
}
private fun startUniMpToPage(context: Context, uniMpId: String, uniMpType: String, pagePath: String){
// 启动直达页面
val configuration = getUniMPOpenConfiguration()
if(uniMpType == "wx"){
configuration.splashClass = UniMPWxSplashView::class.java
}else if("alipay" == uniMpType){
configuration.splashClass = UniMPAlipaySplashView::class.java
}
configuration.path = pagePath
updateUniMp(uniMpId, DCUniMPSDK.getInstance().openUniMP(context, uniMpId, configuration))
} }
private fun releaseWgt(versionEntity: UniVersionEntity, reportViewModel: ReportViewModel, onReleaseWgt: (isSuccess: Boolean, versionEntity: UniVersionEntity) -> Unit) { fun distributeUniMp(
releaseWgt(versionEntity.unimp_id,reportViewModel){ isSuccess -> context: Context,
if(isSuccess){
onReleaseWgt(true, versionEntity)
}else{
onReleaseWgt(false, versionEntity)
}
}
}
//释放资源
private fun releaseWgt(uniMpId: String, reportViewModel: ReportViewModel, onReleaseWgt: (isSuccess: Boolean) -> Unit) {
val appBasePath = DCUniMPSDK.getInstance().getAppBasePath(applicationContext)
val deleteSuccess = File(appBasePath, uniMpId).deleteRecursively()
if(deleteSuccess){
val wgtFile = getWgtFile(uniMpId)
val uniMPReleaseConfiguration = UniMPReleaseConfiguration().apply {
wgtPath = wgtFile.path
password = PreferenceUtil.getUserConfig()?.config?.wgtPassword//"6462"////没有密码可以不写
}
DCUniMPSDK.getInstance().releaseWgtToRunPath(uniMpId, uniMPReleaseConfiguration) { code, _ ->
if (code == 1) {
//释放wgt完成
onReleaseWgt(true)
} else {
//释放wgt失败
CenterToast.show("加载失败,请重试或联系客服!")
onReleaseWgt(false)
File(appBasePath, uniMpId).deleteRecursively()
//事件提交
reportViewModel.requestReport(
ReportRequest(
ReportType.ERROR,
ReportKey.EVENT_CLIENT_UNI_RELEASE_WGT,
uniMpId,
"释放资源失败"
)
)
}
}
}else{
CenterToast.show("加载失败,请重试或联系客服!")
}
}
/**
* 下载wgt文件
*/
fun downloadWGT(context: Context,scope: CoroutineScope, uniVersion: UniVersionEntity, reportViewModel: ReportViewModel = ReportViewModel(), onProgress:(state: UniMpUpdate, filePath: String?, progress: Float?) -> Unit) {
val wgtFile = getWgtFile(uniVersion.unimp_id)
onProgress(UniMpUpdate.DOWNLOAD_START, wgtFile.path, 0f)
downloadUniMp(scope, uniVersion){uniState, filePath, progress ->
onProgress(uniState, filePath, progress)
if(uniState == UniMpUpdate.DOWNLOAD_FINISH){
distributeUniMp(context, uniVersion,reportViewModel) { _ ->}
}
}
}
/**
* 下载并释放资源(但不会启动)
*/
fun downloadReleaseWgt(scope: CoroutineScope, uniVersion: UniVersionEntity,reportViewModel: ReportViewModel, onProgress:(state: UniMpUpdate, progress: Float?) -> Unit,onRelease:(isSuccess: Boolean) -> Unit){
val uniMpId = uniVersion.unimp_id
onProgress(UniMpUpdate.DOWNLOAD_START, 0f)
downloadUniMp(scope, uniVersion){uniState, _, progress ->
onProgress(UniMpUpdate.DOWNLOAD_LOADING, progress)
if(uniState == UniMpUpdate.DOWNLOAD_FINISH){
onProgress(UniMpUpdate.DOWNLOAD_FINISH, 1f)
releaseWgt(uniMpId,reportViewModel){ isSuccess ->
if(isSuccess){
onRelease(true)
}else{
onRelease(false)
}
}
}else if(uniState == UniMpUpdate.DOWNLOAD_FAIL){
onProgress(UniMpUpdate.DOWNLOAD_FAIL, -1f)
}
}
}
//下载资源
private fun downloadUniMp(
scope: CoroutineScope,
uniVersion: UniVersionEntity, uniVersion: UniVersionEntity,
onProgress:(state:UniMpUpdate,filePath: String?, progress: Float) -> Unit reportViewModel: ReportViewModel,
) { pagePath: String? = null,
val extension = MimeTypeMap.getFileExtensionFromUrl(uniVersion.url) onResult: (loading: Boolean) -> Unit,
if(extension != "zip" && extension != "wgt"){ ) = onMain {
CenterToast.show("资源文件格式不被支持...") if (isBusy(uniVersion.unimp_id)) {
onProgress(UniMpUpdate.DOWNLOAD_FAIL, null, -1f) CenterToast.show("请等待模拟器更新完毕!")
onResult(false)
} else if (showRunningUniMp(uniVersion.unimp_id, pagePath)) {
onResult(false)
} else if (isRelease(uniVersion.unimp_id)) {
openUniMp(context, uniVersion.unimp_id, uniVersion.unimp_type, pagePath, reportViewModel, onResult)
} else {
releaseWgt(uniVersion.unimp_id, reportViewModel) { success ->
if (success) {
openUniMp(context, uniVersion.unimp_id, uniVersion.unimp_type, pagePath, reportViewModel, onResult)
} else onResult(false)
}
}
}
fun startUniMpPage(context: Context, uniMpId: String, uniMpType: String, pagePath: String, reportViewModel: ReportViewModel) {
distributeUniMp(context, UniVersionEntity(unimp_id = uniMpId, unimp_type = uniMpType), reportViewModel, pagePath) {}
}
private fun openUniMp(
context: Context,
uniMpId: String,
uniMpType: String,
pagePath: String?,
reportViewModel: ReportViewModel,
onResult: (Boolean) -> Unit,
) = onMain {
try {
val mp = DCUniMPSDK.getInstance().openUniMP(context, uniMpId, getUniMPOpenConfiguration(uniMpType, pagePath))
if (mp == null) {
startupFailure(uniMpId, "上报原因:启动小程序失败", reportViewModel)
} else {
updateUniMp(uniMpId, mp)
}
} catch (e: Exception) {
Log.e(TAG, "启动小程序异常: $uniMpId", e)
startupFailure(uniMpId, "上报原因:启动小程序异常,${e.message.orEmpty()}", reportViewModel)
} finally {
onResult(false)
}
}
private fun startupFailure(uniMpId: String, reason: String, reportViewModel: ReportViewModel) {
updateUniMp(uniMpId, null)
runCatching { getWgtFile(uniMpId).delete() }
report(reportViewModel, ReportType.ERROR, ReportKey.EVENT_CLIENT_UNI_FAIL, uniMpId, reason)
CenterToast.show("加载失败,请重试或联系客服!")
}
private fun releaseWgt(uniMpId: String, reportViewModel: ReportViewModel, onRelease: (Boolean) -> Unit) {
if (!releasing.add(uniMpId)) {
onMain {
CenterToast.show("请等待模拟器更新完毕!")
onRelease(false)
}
return return
} }
releaseExecutor.execute {
val uniMpId = uniVersion.unimp_id try {
val wgtName = getWgtName(uniMpId) val wgtFile = getWgtFile(uniMpId)
val path = FileUtils.instance?.cacheUniAppDir?.absolutePath?:"" check(wgtFile.isFile && wgtFile.length() > 0) { "资源包不存在或为空" }
//先删除旧文件 val config = PreferenceUtil.getUserConfig()?.config
val oldFile = File(path, wgtName) val releaseConfig = UniMPReleaseConfiguration().apply {
if(oldFile.exists()){ wgtPath = wgtFile.absolutePath
password = UniMpPolicy.releasePassword(config?.wgtPassword, config?.uniPassword)
oldFile.delete() }
} DCUniMPSDK.getInstance().releaseWgtToRunPath(uniMpId, releaseConfig) { code, args ->
onProgress(UniMpUpdate.DOWNLOAD_LOADING, null, 0.0f) if (code == 1) {
onMain {
scope.launch { releasing.remove(uniMpId)
val isAvailable = isFileDownloadable(uniVersion.url) onRelease(true)
if(!isAvailable){
onProgress(UniMpUpdate.DOWNLOAD_FAIL, null, -1f)
}else{
UpdateUtils.download(
scope = scope,
url = uniVersion.url,
filePath = path,
fileName = wgtName,
onProgress = {progress->
if(progress.toFloat()/100f>0.1f) {
onProgress(
UniMpUpdate.DOWNLOAD_LOADING,
null,
progress.toFloat() / 100f
)
}
},
onFinish = {isSuccess, filePath ->
if(isSuccess){
PreferenceUtil.saveWgtVersion(uniMpId, uniVersion.version)
onProgress(UniMpUpdate.DOWNLOAD_FINISH, filePath, 1f)
}else{
onProgress(UniMpUpdate.DOWNLOAD_FAIL, filePath, -1f)
CenterToast.show("下载失败...")
} }
} else {
releaseFailure(uniMpId, "SDK 释放失败提示。错误码: $code, 原因提示: $args", reportViewModel, onRelease)
} }
) }
} catch (e: Exception) {
releaseFailure(uniMpId, "释放小程序资源包异常: ${e.message.orEmpty()}", reportViewModel, onRelease)
} }
} }
} }
private fun getUniMPOpenConfiguration(): UniMPOpenConfiguration{ private fun releaseFailure(uniMpId: String, reason: String, reportViewModel: ReportViewModel, onRelease: (Boolean) -> Unit) {
val stringBuilder = StringBuilder() releaseExecutor.execute {
stringBuilder.append("-------------> 📤 header start<-------------\n") runCatching {
stringBuilder.append("│ x-token = ${PreferenceUtil.getXToken()}\n") getWgtFile(uniMpId).delete()
stringBuilder.append("│ x-version = ${getAppVersionName()}\n") val basePath = DCUniMPSDK.getInstance().getAppBasePath(applicationContext)
stringBuilder.append("│ x-platform = android\n") File(basePath, uniMpId).deleteRecursively()
stringBuilder.append("│ x-device-id = ${DeviceIdentifier.getAndroidID(applicationContext)}\n") }.onFailure { Log.w(TAG, "清理失败的小程序资源异常", it) }
stringBuilder.append("│ x-mobile-brand = ${android.os.Build.BRAND}\n") onMain {
stringBuilder.append("│ x-mobile-model = ${android.os.Build.MODEL}\n") releasing.remove(uniMpId)
stringBuilder.append("│ x-channel = ${ChannelUtils.getChannel(applicationContext)}\n") updateUniMp(uniMpId, null)
stringBuilder.append("│ x-package = ${BuildConfig.APPLICATION_ID}\n") Log.e(TAG, reason)
stringBuilder.append("│ x-click-id = ${ChannelUtils.getBdVid(applicationContext)}\n") report(reportViewModel, ReportType.ERROR, ReportKey.EVENT_CLIENT_UNI_RELEASE_WGT, uniMpId, reason)
stringBuilder.append("│ host = ${Constants.RELEASE_BASE_URL}\n") CenterToast.show("加载失败,请重试或联系客服!")
stringBuilder.append("│ decrypt = ${Constants.AESDecrypt}\n") onRelease(false)
stringBuilder.append("│ decrypt = ${Constants.Signature}\n") }
stringBuilder.append("│ isCombo = ok\n") }
stringBuilder.append("-------------> header end <-------------") }
Log.i("UniAppUtils", stringBuilder.toString())
return UniMPOpenConfiguration().apply { /** 新包下载完成后始终重新释放,避免仍启动旧的运行目录。 */
extraData.put("x-token", PreferenceUtil.getXToken()?:"") fun downloadWGT(
extraData.put("x-version", getAppVersionName()?:"") context: Context,
scope: CoroutineScope,
uniVersion: UniVersionEntity,
reportViewModel: ReportViewModel,
pagePath: String? = null,
onProgress: (state: UniMpUpdate, filePath: String?, progress: Float?) -> Unit,
) {
downloadUniMp(scope, uniVersion, reportViewModel, onProgress) {
releaseWgt(uniVersion.unimp_id, reportViewModel) { success ->
if (success) openUniMp(context, uniVersion.unimp_id, uniVersion.unimp_type, pagePath, reportViewModel) {}
}
}
}
fun downloadReleaseWgt(
scope: CoroutineScope,
uniVersion: UniVersionEntity,
reportViewModel: ReportViewModel,
onProgress: (state: UniMpUpdate, progress: Float?) -> Unit,
onRelease: (Boolean) -> Unit,
) {
downloadUniMp(scope, uniVersion, reportViewModel, { state, _, progress ->
onProgress(state, progress)
if (state == UniMpUpdate.DOWNLOAD_FAIL) onRelease(false)
}) {
releaseWgt(uniVersion.unimp_id, reportViewModel, onRelease)
}
}
private fun downloadUniMp(
scope: CoroutineScope,
version: UniVersionEntity,
reportViewModel: ReportViewModel,
onProgress: (UniMpUpdate, String?, Float?) -> Unit,
onDownloaded: () -> Unit,
) = onMain {
val id = version.unimp_id
if (id in releasing || !downloading.add(id)) {
CenterToast.show("请等待模拟器更新完毕!")
return@onMain
}
scope.launch(Dispatchers.Main.immediate, start = CoroutineStart.UNDISPATCHED) {
var failureReported = false
var downloadCompleted = false
try {
onProgress(UniMpUpdate.DOWNLOAD_START, null, 0f)
val file = getWgtFile(id)
val result = downloader.download(UniMpPolicy.downloadUrls(version), file,
onProgress = { progress -> withContext(Dispatchers.Main) { onProgress(UniMpUpdate.DOWNLOAD_LOADING, null, progress) } },
onFailure = { url, elapsed, reason ->
failureReported = true
report(reportViewModel, ReportType.ERROR, ReportKey.EVENT_CLIENT_DOWNLOAD_UNIMP_ERROR, reason,
"下载地址:$url 持续时间:${elapsed / 1000f}秒 上报原因:$reason")
})
downloadCompleted = true
PreferenceUtil.saveWgtVersion(id, version.version)
val time = String.format(Locale.CHINA, "%.2f", result.elapsedMillis / 1000.0)
report(reportViewModel, ReportType.CLICK, ReportKey.EVENT_CLIENT_DOWNLOAD_UNIMP_SUCCESS, "下载时间:${time}s",
"下载地址:${result.url} 持续时间:${time}秒 上报原因:下载完成。")
} catch (e: CancellationException) {
withContext(NonCancellable + Dispatchers.Main) { onProgress(UniMpUpdate.DOWNLOAD_FAIL, null, -1f) }
throw e
} catch (e: Exception) {
Log.e(TAG, "下载小程序失败: $id", e)
if (!failureReported || downloadCompleted) {
report(reportViewModel, ReportType.ERROR, ReportKey.EVENT_CLIENT_DOWNLOAD_UNIMP_ERROR, e.message.orEmpty(), "处理小程序资源包失败: $id,${e.message.orEmpty()}")
}
CenterToast.show("打开失败,请重试或联系客服")
onProgress(UniMpUpdate.DOWNLOAD_FAIL, null, -1f)
return@launch
} finally {
downloading.remove(id)
}
onProgress(UniMpUpdate.DOWNLOAD_FINISH, getWgtFile(id).path, 1f)
onDownloaded()
}
}
private fun getUniMPOpenConfiguration(uniType: String, pagePath: String?): UniMPOpenConfiguration =
UniMPOpenConfiguration().apply {
path = pagePath
splashClass = if (uniType == "alipay") UniMPAlipaySplashView::class.java else UniMPWxSplashView::class.java
extraData.put("x-token", PreferenceUtil.getXToken().orEmpty())
extraData.put("x-version", getAppVersionName().orEmpty())
extraData.put("x-platform", "android") extraData.put("x-platform", "android")
extraData.put("x-device-id", DeviceIdentifier.getAndroidID(applicationContext)) extraData.put("x-device-id", DeviceIdentifier.getAndroidID(applicationContext))
extraData.put("x-mobile-brand", android.os.Build.BRAND) extraData.put("x-mobile-brand", android.os.Build.BRAND)
extraData.put("x-mobile-model", android.os.Build.MODEL) extraData.put("x-mobile-model", android.os.Build.MODEL)
extraData.put("x-channel", ChannelUtils.getChannel(applicationContext)) extraData.put("x-channel", ChannelUtils.getChannel(applicationContext))
extraData.put("x-package", BuildConfig.APPLICATION_ID) extraData.put("x-package", BuildConfig.APPLICATION_ID)
extraData.put("x-click-id",ChannelUtils.getBdVid(applicationContext)) extraData.put("x-click-id", ChannelUtils.getBdVid(applicationContext))
extraData.put("host", "${Constants.RELEASE_BASE_URL}/") extraData.put("host", "${Constants.RELEASE_BASE_URL.trimEnd('/')}/")
extraData.put("decrypt", Constants.AESDecrypt) extraData.put("decrypt", Constants.AESDecrypt)
extraData.put("encrypt", Constants.Signature) extraData.put("encrypt", Constants.Signature)
extraData.put("isCombo", "ok") extraData.put("isCombo", "ok")
} }
}
/**
* 拉起微信小程序来支付
*/
fun startUniPay(api: IWXAPI, weixinMpOriId: String, outTradeNo: String) { fun startUniPay(api: IWXAPI, weixinMpOriId: String, outTradeNo: String) {
//isStartComboPay = true val request = WXLaunchMiniProgram.Req().apply {
val req = WXLaunchMiniProgram.Req() userName = weixinMpOriId
req.userName = weixinMpOriId // 填小程序原始id path = "pages/index/index?outTradeNo=$outTradeNo"
req.path = "pages/index/index?outTradeNo=$outTradeNo" //拉起小程序页面的可带参路径,不填默认拉起小程序首页,对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar"。 miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE
req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE// 可选打开 开发版,体验版和正式版
api.sendReq(req)
}
private val okHttpClient: OkHttpClient by lazy {
OkHttpClient.Builder()
// 如果需要,可以在这里配置超时、缓存等
// .connectTimeout(15, TimeUnit.SECONDS)
.build()
}
suspend fun isFileDownloadable(url: String): Boolean = withContext(Dispatchers.IO) {
val request = Request.Builder().url(url).build()
try {
okHttpClient.newCall(request).execute().use { response ->
val body = response.body
val fileSize = body.contentLength()
// 下载文件小于1KB,需要判断Url是否可靠
if (fileSize < 1024) {
val result = response.isSuccessful
return@withContext result
} else {
return@withContext true
}
}
} catch (e: Exception) {
e.printStackTrace()
} }
return@withContext false api.sendReq(request)
} }
private fun report(viewModel: ReportViewModel, type: String, key: String, value: String, extra: String) {
viewModel.requestReport(ReportRequest(type = type, key = key, value = value, extra = extra))
}
private fun onMain(action: () -> Unit) {
if (Looper.myLooper() == Looper.getMainLooper()) action() else mainHandler.post { action() }
}
} }
enum class UniMpUpdate{ enum class UniMpUpdate {
DOWNLOAD_START, DOWNLOAD_START,
DOWNLOAD_LOADING, DOWNLOAD_LOADING,
DOWNLOAD_FINISH, DOWNLOAD_FINISH,
DOWNLOAD_FAIL DOWNLOAD_FAIL,
} }

View File

@ -0,0 +1,206 @@
package com.img.rabbit.utils
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import java.util.concurrent.TimeUnit
/** 每个小程序独立下载;按 urls 顺序重试,重试期间展示进度不回退。 */
internal class UniMpDownloader(
private val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.callTimeout(60, TimeUnit.SECONDS)
.build(),
) {
data class Result(val url: String, val elapsedMillis: Long)
suspend fun download(
urls: List<String>,
destination: File,
onProgress: suspend (Float) -> Unit,
onFailure: suspend (url: String, elapsedMillis: Long, reason: String) -> Unit,
): Result = withContext(Dispatchers.IO) {
val started = System.nanoTime()
val temporary = File(destination.parentFile, "${destination.nameWithoutExtension}_cache.wgt")
val progressMutex = Mutex()
var maximumProgress = 0
var lastError: Exception = IOException("url为空!")
try {
for (url in urls.ifEmpty { listOf("") }) {
currentCoroutineContext().ensureActive()
val attemptStarted = System.nanoTime()
try {
val directory = destination.parentFile ?: throw IOException("下载目录不存在")
if (!directory.isDirectory && !directory.mkdirs()) throw IOException("无法创建下载目录")
if (temporary.exists() && !temporary.delete()) throw IOException("无法清理下载缓存")
if (url.isBlank()) throw IOException("url为空!")
downloadUrl(url, temporary, attemptStarted) { current, total ->
val percent = if (total > 0) (current * 100 / total).coerceIn(0, 99).toInt() else 0
progressMutex.withLock {
if (percent > maximumProgress) {
maximumProgress = percent
onProgress(percent / 100f)
}
}
}
currentCoroutineContext().ensureActive()
if (temporary.length() == 0L) throw IOException("资源包为空")
// 仅完整下载的包才能替换正式 wgt,SDK 要求文件名为 unimp_id.wgt。
if (destination.exists() && !destination.delete()) throw IOException("无法替换资源包")
if (!temporary.renameTo(destination)) throw IOException("复制资源包失败")
return@withContext Result(url, elapsedMillis(started))
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
currentCoroutineContext().ensureActive()
lastError = e
onFailure(url, elapsedMillis(attemptStarted), e.message?.takeIf { it.isNotBlank() } ?: "Url连接错误")
}
}
throw lastError
} finally {
temporary.delete()
}
}
private suspend fun downloadUrl(
url: String,
file: File,
started: Long,
onProgress: suspend (Long, Long) -> Unit,
) {
var rangedSize = 0L
request(Request.Builder().url(url).header("Accept-Encoding", "identity").build()) { response ->
if (!response.isSuccessful) throw IOException("HTTP ${response.code}: ${response.message}")
val total = response.body.contentLength()
if (total > CHUNK_SIZE && response.header("Accept-Ranges").equals("bytes", ignoreCase = true)) {
rangedSize = total
} else {
var received = 0L
var lastProgressTime = 0L
response.body.byteStream().use { input ->
file.outputStream().use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
checkActive(started)
val count = input.read(buffer)
if (count == -1) break
output.write(buffer, 0, count)
received += count
val now = elapsedMillis(started)
if (now - lastProgressTime >= 500) {
onProgress(received, total)
lastProgressTime = now
}
}
}
}
if (total >= 0 && received != total) throw IOException("资源包长度不匹配: $received/$total")
onProgress(received, total)
}
}
if (rangedSize > 0) downloadChunks(url, file, rangedSize, started, onProgress)
}
private suspend fun downloadChunks(
url: String,
file: File,
total: Long,
started: Long,
onProgress: suspend (Long, Long) -> Unit,
) = coroutineScope {
RandomAccessFile(file, "rw").use { it.setLength(total) }
val permits = Semaphore(MAX_THREADS)
val progressMutex = Mutex()
var received = 0L
var lastProgressTime = 0L
(0L until total step CHUNK_SIZE).map { start ->
async {
permits.withPermit {
val end = minOf(start + CHUNK_SIZE - 1, total - 1)
val request = Request.Builder().url(url)
.header("Accept-Encoding", "identity")
.header("Range", "bytes=$start-$end").build()
request(request) { response ->
if (response.code != 206 || response.header("Content-Range") != "bytes $start-$end/$total") {
throw IOException("无效的分块响应: HTTP ${response.code}")
}
var chunkSize = 0L
response.body.byteStream().use { input ->
RandomAccessFile(file, "rw").use { output ->
output.seek(start)
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
checkActive(started)
val count = input.read(buffer)
if (count == -1) break
chunkSize += count
if (chunkSize > end - start + 1) throw IOException("分块长度超出范围")
output.write(buffer, 0, count)
progressMutex.withLock {
received += count
val now = elapsedMillis(started)
if (now - lastProgressTime >= 500) {
onProgress(received, total)
lastProgressTime = now
}
}
}
}
}
if (chunkSize != end - start + 1) throw IOException("分块数据不完整")
}
}
}
}.awaitAll()
onProgress(received, total)
}
private suspend fun <T> request(request: Request, block: suspend (Response) -> T): T = coroutineScope {
val call = client.newCall(request)
// 取消页面任务或某个分块失败时,及时终止其余网络请求。
val cancellation = launch(start = CoroutineStart.UNDISPATCHED) {
try {
awaitCancellation()
} finally {
call.cancel()
}
}
try {
call.execute().use { block(it) }
} finally {
cancellation.cancel()
}
}
private suspend fun checkActive(started: Long) {
currentCoroutineContext().ensureActive()
if (elapsedMillis(started) > 60_000) throw IOException("超时下载")
}
private fun elapsedMillis(started: Long) = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)
private companion object {
const val CHUNK_SIZE = 10 * 1024 * 1024L
const val MAX_THREADS = 8
}
}

View File

@ -0,0 +1,27 @@
package com.img.rabbit.utils
import com.img.rabbit.bean.response.UniVersionEntity
/** 与 weiquan-android 的资源配置、强更和密码规则保持一致。 */
internal object UniMpPolicy {
fun releasePassword(wgtPassword: String?, uniPassword: String?): String? {
val prefix = wgtPassword.orEmpty().let { if (it.length > 10) it.substring(10) else it }
return (prefix + uniPassword.orEmpty()).takeIf { it.isNotEmpty() }
}
fun downloadUrls(version: UniVersionEntity): List<String> =
version.urls?.takeIf { it.isNotEmpty() } ?: listOf(version.url)
fun requiresDownload(force: Boolean, hasPackage: Boolean): Boolean = force || !hasPackage
fun isNewer(version: String, installedVersion: String): Boolean {
val newer = version.split('.')
val installed = installedVersion.split('.')
if (newer.size != 3 || installed.size != 3) return false
for (i in 0..2) {
val comparison = (newer[i].toIntOrNull() ?: 0).compareTo(installed[i].toIntOrNull() ?: 0)
if (comparison != 0) return comparison > 0
}
return false
}
}

View File

@ -37,6 +37,11 @@ import com.img.rabbit.utils.MMKVUtils
import com.img.rabbit.utils.StringUtils import com.img.rabbit.utils.StringUtils
import com.tencent.mm.opensdk.modelmsg.SendAuth import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI import com.tencent.mm.opensdk.openapi.IWXAPI
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resume
import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@ -130,91 +135,55 @@ class LoginViewModel : BaseViewModel() {
} }
} }
fun oneKeyLoginForGeTuiSdk(activity: Activity, onShowOneKeyScreen:(Boolean)->Unit) { /** 登录页进入时优先预取本机号码;失败、超时或结果无效时交由页面回退。 */
// 初始化 SDK suspend fun prepareOneKeyLogin(activity: Activity): Boolean = withContext(Dispatchers.Main.immediate) {
GYManager.getInstance().init(GyConfig.with(activity.applicationContext).callBack(object : GyCallBack { oneKeyPreLogin = null
override fun onSuccess(response: GYResponse?) { isGYUIDValid.value = false
if (!PreferenceUtil.getAgreement()) return@withContext false
try {
withTimeoutOrNull(12_000L) {
val manager = GYManager.getInstance()
awaitGyResponse { callback ->
manager.init(GyConfig.with(activity.applicationContext).callBack(callback).build())
} ?: return@withTimeoutOrNull false
isGYUIDValid.value = true isGYUIDValid.value = true
Log.i(ONEKEY_TAG, "--->初始化: onSuccess")
//预登录(提高拉起速度,可选但推荐) val response = awaitGyResponse { callback -> manager.ePreLogin(8000, callback) }
GYManager.getInstance().ePreLogin(/* timeout = */ 8000, /* gyCallBack = */ object : GyCallBack { ?: return@withTimeoutOrNull false
override fun onSuccess(response: GYResponse?) { val data = response.msg?.takeIf { it.isNotBlank() }
Log.i(ONEKEY_TAG, "--->预登录: onSuccess--->${response}") ?: return@withTimeoutOrNull false
val preLoginData = response?.msg val result = Json { ignoreUnknownKeys = true }.decodeFromString<OnekeyPreLogin>(data)
if (!preLoginData.isNullOrEmpty()) { if (result.errorCode != 0 || result.number.isBlank() ||
try { !manager.isPreLoginResultValid || manager.preLoginResult == null) {
val json = Json { ignoreUnknownKeys = true } return@withTimeoutOrNull false
oneKeyPreLogin =
json.decodeFromString<OnekeyPreLogin>(preLoginData)
// 打印解析后的详细数据
Log.i(ONEKEY_TAG, "=== 预登录数据解析结果 ===")
Log.i(ONEKEY_TAG, "流程ID: ${oneKeyPreLogin?.process_id}")
Log.i(ONEKEY_TAG, "运营商类型: ${oneKeyPreLogin?.operatorType}")
Log.i(ONEKEY_TAG, "客户端类型: ${oneKeyPreLogin?.clienttype}")
Log.i(ONEKEY_TAG, "访问码: ${oneKeyPreLogin?.accessCode}")
Log.i(ONEKEY_TAG, "手机号: ${oneKeyPreLogin?.number}")
Log.i(ONEKEY_TAG, "过期时间: ${oneKeyPreLogin?.expiredTime}")
Log.i(ONEKEY_TAG, "错误码: ${oneKeyPreLogin?.errorCode}")
Log.i(ONEKEY_TAG, "错误描述: ${oneKeyPreLogin?.errorDesc}")
Log.i(ONEKEY_TAG, "耗时: ${oneKeyPreLogin?.costTime}ms")
Log.i(ONEKEY_TAG, "================================")
// 根据解析结果决定是否继续(根据errorCode判断)
if (oneKeyPreLogin?.errorCode == 0) {
oneKeyLoginValid(onShowOneKeyScreen = onShowOneKeyScreen)
} else {
onShowOneKeyScreen(false)
Log.e(ONEKEY_TAG, "预登录校验失败: ${oneKeyPreLogin?.errorDesc}")
}
} catch (e: Exception) {
Log.e(ONEKEY_TAG, "JSON解析失败: ${e.message}")
Log.e(ONEKEY_TAG, "原始数据: $preLoginData")
// 解析失败时继续执行原逻辑
onShowOneKeyScreen(false)
}
}
}
override fun onFailed(response: GYResponse?) {
onShowOneKeyScreen(false)
Log.i(ONEKEY_TAG, "--->预登录: onFailed--->${response}")
}
})
}
override fun onFailed(response: GYResponse?) {
onShowOneKeyScreen(false)
Log.i(ONEKEY_TAG, "--->初始化: onFailed--->${response}")
}
}).build())
}
private fun oneKeyLoginValid(onShowOneKeyScreen:(Boolean)->Unit) {
if (GYManager.getInstance().isPreLoginResultValid) {
//预登录有效,启动登录授权页
onShowOneKeyScreen(true)
Log.i(ONEKEY_TAG, "--->预登录校验有效A: onSuccess")
} else {
//考虑到是用户在等待,建议超时8s以上,至少设置5s以上
GYManager.getInstance().ePreLogin(5000, object : GyCallBack {
override fun onSuccess(response: GYResponse?) {
//预登录成功,启动登录授权页
onShowOneKeyScreen(true)
Log.i(ONEKEY_TAG, "--->预登录校验有效B: onSuccess--->${response}")
} }
oneKeyPreLogin = result
override fun onFailed(response: GYResponse?) { true
//预登录失败,提示用户稍后重试 } ?: false
onShowOneKeyScreen(false) } catch (e: CancellationException) {
Log.i(ONEKEY_TAG, "--->预登录校验有效B: onFailed--->${response}") // 页面退出时取消等待,不让迟到的 SDK 回调切换后续页面。
} throw e
}) } catch (e: Exception) {
Log.w(ONEKEY_TAG, "一键登录准备失败,回退验证码登录", e)
false
} }
} }
private suspend fun awaitGyResponse(start: (GyCallBack) -> Unit): GYResponse? =
suspendCancellableCoroutine { continuation ->
val completed = AtomicBoolean(false)
fun complete(response: GYResponse?) {
if (completed.compareAndSet(false, true) && continuation.isActive) {
continuation.resume(response)
}
}
start(object : GyCallBack {
override fun onSuccess(response: GYResponse?) = complete(response)
override fun onFailed(response: GYResponse?) = complete(null)
})
}
fun requestOneKeyLogin(gyuid: String, token: String) { fun requestOneKeyLogin(gyuid: String, token: String) {
// 调用 API 获取数据 // 调用 API 获取数据
val jsonOneKey = JsonObject() val jsonOneKey = JsonObject()

View File

@ -1,20 +1,31 @@
package com.img.rabbit.viewmodel package com.img.rabbit.viewmodel
import android.util.Log import android.util.Log
import androidx.lifecycle.viewModelScope
import com.img.rabbit.bean.request.ReportRequest import com.img.rabbit.bean.request.ReportRequest
import com.img.rabbit.provider.api.ApiManager import com.img.rabbit.provider.api.ApiManager
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.RequestBody.Companion.toRequestBody
class ReportViewModel : BaseViewModel() { class ReportViewModel : BaseViewModel() {
private val TAG = "ReportViewModel" private val TAG = "ReportViewModel"
//请求客服连接 fun requestReport(request: ReportRequest){
fun requestReport(requst: ReportRequest){ viewModelScope.launch(Dispatchers.IO) {
mLaunch { try {
val requstJson = Json.encodeToString(requst) val body = Json.encodeToString(request)
val response = ApiManager.serviceVo.report(requstJson.toRequestBody()) .toRequestBody("application/json; charset=utf-8".toMediaType())
Log.i(TAG, "requestReport: ${response.data}") ApiManager.serviceVo.report(body)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
// 上报失败不干扰下载重试和启动界面。
Log.w(TAG, "事件上报失败", e)
}
} }
} }
} }