Compare commits
No commits in common. "Dev_Batiao_Sdk" and "master" have entirely different histories.
Dev_Batiao
...
master
|
|
@ -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="25" />
|
<bytecodeTargetLevel target="21" />
|
||||||
</component>
|
</component>
|
||||||
</project>
|
</project>
|
||||||
|
|
@ -3,39 +3,6 @@
|
||||||
<component name="deploymentTargetSelector">
|
<component name="deploymentTargetSelector">
|
||||||
<selectionStates>
|
<selectionStates>
|
||||||
<SelectionState runConfigName="app">
|
<SelectionState runConfigName="app">
|
||||||
<option name="selectionMode" value="DROPDOWN" />
|
|
||||||
<DropdownSelection timestamp="2026-11-09T09:16:20.249736600Z">
|
|
||||||
<Target type="DEFAULT_BOOT">
|
|
||||||
<handle>
|
|
||||||
<DeviceId pluginId="PhysicalDevice" identifier="serial=Y5DELZR46DZTCI9D" />
|
|
||||||
</handle>
|
|
||||||
</Target>
|
|
||||||
</DropdownSelection>
|
|
||||||
<DialogSelection />
|
|
||||||
</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" />
|
<option name="selectionMode" value="DROPDOWN" />
|
||||||
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z">
|
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z">
|
||||||
<Target type="DEFAULT_BOOT">
|
<Target type="DEFAULT_BOOT">
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
<?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_25" default="true" project-jdk-name="jbr-25" project-jdk-type="JavaSDK">
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" 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">
|
||||||
|
|
|
||||||
|
|
@ -2,26 +2,13 @@ import org.gradle.kotlin.dsl.api
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id("com.android.application")
|
id("com.android.application")
|
||||||
id("com.batiao.batiaosdkbuilder") version "1.0.398"
|
|
||||||
alias(libs.plugins.compose.compiler)
|
alias(libs.plugins.compose.compiler)
|
||||||
kotlin("plugin.serialization") version "2.3.0"
|
kotlin("plugin.serialization") version "2.3.0"
|
||||||
}
|
}
|
||||||
|
|
||||||
batiaoSdkConfig {
|
|
||||||
// 业务 API 显式挂载 SignInterceptor;全局注入会修改图片/WGT 等下载 URL。
|
|
||||||
// BatiaoUnimp 自带 SignInterceptor,不依赖全局注入。
|
|
||||||
enableHttpAuth = false
|
|
||||||
unimp = true
|
|
||||||
// 与 weiquan-android 一致,只在用户同意隐私协议后初始化。
|
|
||||||
applicationHookMethod = "initializeBatiaoAfterConsent"
|
|
||||||
sdkVersion = "1.0.398"
|
|
||||||
prop("signKey", "xn08hYoizXhZ1zHP8DVqfCm2yHxPmhil")
|
|
||||||
prop("decodeKey", "e4rOtnF8tJjtHO7ecZeJHN1rapED5ImB")
|
|
||||||
}
|
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "com.img.rabbit"
|
namespace = "com.img.rabbit"
|
||||||
compileSdk = 37
|
compileSdk = 36
|
||||||
|
|
||||||
buildFeatures {
|
buildFeatures {
|
||||||
compose = true
|
compose = true
|
||||||
|
|
@ -44,15 +31,16 @@ android {
|
||||||
}
|
}
|
||||||
|
|
||||||
composeOptions {
|
composeOptions {
|
||||||
|
// 注意:Kotlin 1.8.x 以后建议检查与 Compose 编译器的版本兼容性
|
||||||
kotlinCompilerExtensionVersion = "1.4.8"
|
kotlinCompilerExtensionVersion = "1.4.8"
|
||||||
}
|
}
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "com.img.rabbit"
|
applicationId = "com.img.rabbit"
|
||||||
minSdk = 24
|
minSdk = 24
|
||||||
targetSdk = 37
|
targetSdk = 36
|
||||||
versionCode = 3
|
versionCode = 1
|
||||||
versionName = "1.0.3"
|
versionName = "1.0.0"
|
||||||
multiDexEnabled = true
|
multiDexEnabled = true
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
|
@ -62,8 +50,7 @@ android {
|
||||||
}
|
}
|
||||||
|
|
||||||
ndk {
|
ndk {
|
||||||
// Batiao 1.0.398 仅提供 arm64-v8a 的原生库。
|
abiFilters.addAll(listOf("arm64-v8a", "x86_64", "x86", "armeabi-v7a"))
|
||||||
abiFilters.add("arm64-v8a")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 仅保留基础占位符,渠道相关的移至下方 flavor 处理
|
// 仅保留基础占位符,渠道相关的移至下方 flavor 处理
|
||||||
|
|
@ -176,8 +163,6 @@ tasks.withType<JavaCompile>().configureEach {
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
// 手动启动延后到隐私授权之后的初始化器。
|
|
||||||
implementation("androidx.startup:startup-runtime:1.2.0")
|
|
||||||
api(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar","*.aar"))))
|
api(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar","*.aar"))))
|
||||||
// 基础依赖
|
// 基础依赖
|
||||||
implementation(libs.androidx.core.ktx)
|
implementation(libs.androidx.core.ktx)
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,9 @@
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
xmlns:tools="http://schemas.android.com/tools">
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
<!-- 不允许依赖库重新引入读取安装列表/运行任务的权限。 -->
|
|
||||||
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:node="remove" />
|
|
||||||
<uses-permission android:name="android.permission.GET_TASKS" tools:node="remove" />
|
|
||||||
<uses-permission android:name="android.permission.REAL_GET_TASKS" tools:node="remove" />
|
|
||||||
<!-- 在Android14及以上版本读取SelectedPhotoAccess需要添加READ_MEDIA_VISUAL_USER_SELECTED权限 -->
|
<!-- 在Android14及以上版本读取SelectedPhotoAccess需要添加READ_MEDIA_VISUAL_USER_SELECTED权限 -->
|
||||||
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
|
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
|
||||||
<!-- 写入外部存储权限,用于截长图保存,主要兼容Android 13及以下版本(Android13以上高版本不需要,但低版本必须) -->
|
<!-- 写入外部存储权限,用于保存拍照后的图片或者下载文件,主要兼容Android 13及以下版本(Android13以上高版本不需要,但低版本必须) -->
|
||||||
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"
|
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"
|
||||||
android:maxSdkVersion="32"
|
android:maxSdkVersion="32"
|
||||||
tools:ignore="ScopedStorage" />
|
tools:ignore="ScopedStorage" />
|
||||||
|
|
@ -41,7 +37,7 @@
|
||||||
<package android:name="com.eg.android.AlipayGphone" /> <!-- 支付宝 -->
|
<package android:name="com.eg.android.AlipayGphone" /> <!-- 支付宝 -->
|
||||||
<package android:name="hk.alipay.wallet" /> <!-- AlipayHK -->
|
<package android:name="hk.alipay.wallet" /> <!-- AlipayHK -->
|
||||||
<package android:name="com.tencent.mm" />
|
<package android:name="com.tencent.mm" />
|
||||||
<intent tools:node="remove">
|
<intent>
|
||||||
<action android:name="com.getui.sdk.action" />
|
<action android:name="com.getui.sdk.action" />
|
||||||
</intent>
|
</intent>
|
||||||
</queries>
|
</queries>
|
||||||
|
|
@ -66,20 +62,6 @@
|
||||||
tools:replace="android:allowBackup,android:supportsRtl"
|
tools:replace="android:allowBackup,android:supportsRtl"
|
||||||
tools:targetApi="33">
|
tools:targetApi="33">
|
||||||
|
|
||||||
<!-- SDK 自动初始化发生在 Application.onCreate 之前,改为同意后手动初始化。 -->
|
|
||||||
<provider android:name="com.google.mlkit.common.internal.MlKitInitProvider"
|
|
||||||
tools:node="remove" />
|
|
||||||
<provider android:name="com.getui.gtc.base.GtcProvider" tools:node="remove" />
|
|
||||||
<provider android:name=".provider.ConsentGtcProvider"
|
|
||||||
android:authorities="${applicationId}.getui.gtc.provider"
|
|
||||||
android:exported="false" />
|
|
||||||
<provider android:name="androidx.startup.InitializationProvider"
|
|
||||||
android:authorities="${applicationId}.androidx-startup"
|
|
||||||
tools:node="merge">
|
|
||||||
<meta-data android:name="okhttp3.internal.platform.PlatformInitializer"
|
|
||||||
tools:node="remove" />
|
|
||||||
</provider>
|
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name="com.img.rabbit.MainActivity"
|
android:name="com.img.rabbit.MainActivity"
|
||||||
android:theme="@style/SplashTheme"
|
android:theme="@style/SplashTheme"
|
||||||
|
|
@ -121,16 +103,6 @@
|
||||||
|
|
||||||
|
|
||||||
<!--如果是小程序模式,还需要添加这行配置-->
|
<!--如果是小程序模式,还需要添加这行配置-->
|
||||||
<activity
|
|
||||||
android:name=".wxapi.AuthorizedWXEntryActivity"
|
|
||||||
android:exported="false"
|
|
||||||
android:excludeFromRecents="true"
|
|
||||||
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
|
|
||||||
<activity
|
|
||||||
android:name=".wxapi.AuthorizedWXPayEntryActivity"
|
|
||||||
android:exported="false"
|
|
||||||
android:launchMode="singleTop"
|
|
||||||
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
|
|
||||||
<activity
|
<activity
|
||||||
android:name="io.dcloud.feature.payment.weixin.WXPayProcessMeadiatorActivity"
|
android:name="io.dcloud.feature.payment.weixin.WXPayProcessMeadiatorActivity"
|
||||||
android:excludeFromRecents="true"
|
android:excludeFromRecents="true"
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
package com.img.rabbit
|
package com.img.rabbit
|
||||||
|
|
||||||
|
import android.app.ActivityManager
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
|
@ -7,70 +8,56 @@ import android.util.Log
|
||||||
import com.bumptech.glide.Glide
|
import com.bumptech.glide.Glide
|
||||||
import com.img.rabbit.utils.NetworkMonitor
|
import com.img.rabbit.utils.NetworkMonitor
|
||||||
import com.g.gysdk.GYManager
|
import com.g.gysdk.GYManager
|
||||||
import androidx.startup.AppInitializer
|
import com.getui.gtc.base.util.CommonUtil.isMainProcess
|
||||||
import com.google.mlkit.common.sdkinternal.MlKitContext
|
|
||||||
import com.github.gzuliyujiang.oaid.DeviceID
|
import com.github.gzuliyujiang.oaid.DeviceID
|
||||||
import com.github.gzuliyujiang.oaid.IGetter
|
import com.github.gzuliyujiang.oaid.IGetter
|
||||||
import com.img.rabbit.config.Constants
|
import com.img.rabbit.config.Constants
|
||||||
import com.img.rabbit.provider.storage.PreferenceUtil
|
import com.img.rabbit.provider.storage.PreferenceUtil
|
||||||
import com.img.rabbit.provider.storage.PrivacyConsentStore
|
|
||||||
import com.img.rabbit.provider.ConsentGtcProvider
|
|
||||||
import com.img.rabbit.provider.utils.HeadParamUtils
|
|
||||||
import com.img.rabbit.uni.UniMPImmersiveWindow
|
|
||||||
import com.img.rabbit.utils.ChannelUtils
|
import com.img.rabbit.utils.ChannelUtils
|
||||||
import com.tencent.mmkv.MMKV
|
import com.tencent.mmkv.MMKV
|
||||||
import com.umeng.analytics.MobclickAgent
|
import com.umeng.analytics.MobclickAgent
|
||||||
import com.umeng.commonsdk.UMConfigure
|
import com.umeng.commonsdk.UMConfigure
|
||||||
import com.umeng.socialize.PlatformConfig
|
import com.umeng.socialize.PlatformConfig
|
||||||
import okhttp3.internal.platform.PlatformInitializer
|
import io.dcloud.common.util.RuningAcitvityUtil
|
||||||
import io.dcloud.feature.sdk.DCSDKInitConfig
|
import io.dcloud.feature.sdk.DCSDKInitConfig
|
||||||
import io.dcloud.feature.sdk.DCUniMPSDK
|
import io.dcloud.feature.sdk.DCUniMPSDK
|
||||||
import io.dcloud.feature.sdk.MenuActionSheetItem
|
import io.dcloud.feature.sdk.MenuActionSheetItem
|
||||||
import java.lang.Exception
|
import java.lang.Exception
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
|
|
||||||
class BaseApplication : Application() {
|
class BaseApplication : Application() {
|
||||||
private val TAG = "BaseApplication"
|
private val TAG = "BaseApplication"
|
||||||
private var batiaoInitialized = false
|
|
||||||
private var thirdPartyInitialized = false
|
|
||||||
private var uniAppInitialized = false
|
|
||||||
private var uniAppOaid: String? = null
|
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
|
// 只有是主进程时,才执行重量级初始化
|
||||||
|
if (getProcessName(this) == packageName) {
|
||||||
|
Log.i(TAG, "进行必要的SDK初始化...")
|
||||||
|
// 初始化MMKV
|
||||||
|
initMMKV()
|
||||||
|
// 非小程序进程(使用unimp 关键字 可以根据宿主的具体情况进行调整)
|
||||||
|
if (PreferenceUtil.getAgreement() && !RuningAcitvityUtil.getAppName(baseContext).contains("unimp")) {
|
||||||
|
Log.i(TAG, "已同意隐私政策,BaseApplication开始初始化SDK服务...")
|
||||||
initThirdParty()
|
initThirdParty()
|
||||||
|
initUM()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun attachBaseContext(base: Context?) {
|
override fun attachBaseContext(base: Context?) {
|
||||||
|
//MultiDex.install(base)
|
||||||
super.attachBaseContext(base)
|
super.attachBaseContext(base)
|
||||||
PrivacyConsentStore.initialize(this)
|
|
||||||
HeadParamUtils.applicationContext = this
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 隐私同意即可初始化
|
* 隐私同意即可初始化
|
||||||
*/
|
*/
|
||||||
@Synchronized
|
|
||||||
fun initThirdParty(){
|
fun initThirdParty(){
|
||||||
if (!PrivacyConsentStore.isAccepted() || thirdPartyInitialized) return
|
//需要在隐私框架下才能处理的逻辑
|
||||||
// 独立进程也必须先检查授权;只注册其所需的窗口适配。
|
if(PreferenceUtil.getAgreement()){
|
||||||
UniMPImmersiveWindow.register(this)
|
|
||||||
if (currentProcessName() == packageName) {
|
|
||||||
initMMKV()
|
|
||||||
AppInitializer.getInstance(this).initializeComponent(PlatformInitializer::class.java)
|
|
||||||
MlKitContext.initializeIfNeeded(this)
|
|
||||||
// 采集开关必须在任何 SDK(包括构建插件注入代码)启动前设置。
|
|
||||||
UMConfigure.enableAplCollection(false)
|
|
||||||
check(GYManager.getInstance().setSecurity(this, false)) {
|
|
||||||
"无法关闭个验扩展采集"
|
|
||||||
}
|
|
||||||
ConsentGtcProvider.initializeAfterConsent(this)
|
|
||||||
if (!batiaoInitialized) {
|
|
||||||
initializeBatiaoAfterConsent()
|
|
||||||
batiaoInitialized = true
|
|
||||||
}
|
|
||||||
Log.i(TAG, "用户已同意隐私政策,开始初始化第三方服务")
|
Log.i(TAG, "用户已同意隐私政策,开始初始化第三方服务")
|
||||||
// 初始化网络状态监控
|
// 初始化网络状态监控
|
||||||
NetworkMonitor.initialize(this)
|
NetworkMonitor.initialize(this)
|
||||||
|
|
@ -78,15 +65,9 @@ class BaseApplication : Application() {
|
||||||
Glide.get(this)
|
Glide.get(this)
|
||||||
// 初始化个推SDK
|
// 初始化个推SDK
|
||||||
initGeTuiOneKeyLogin()
|
initGeTuiOneKeyLogin()
|
||||||
initUM()
|
|
||||||
// 初始化OAID和uni-app SDK
|
// 初始化OAID和uni-app SDK
|
||||||
initOAIDAndUniAPPSdk()
|
initOAIDAndUniAPPSdk()
|
||||||
}
|
}
|
||||||
thirdPartyInitialized = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Batiao 构建插件只向此方法注入初始化,调用前必须检查隐私协议。
|
|
||||||
private fun initializeBatiaoAfterConsent() {
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -133,11 +114,7 @@ class BaseApplication : Application() {
|
||||||
|
|
||||||
//初始化uni-app SDK
|
//初始化uni-app SDK
|
||||||
private fun initUniAPPSdk() {
|
private fun initUniAPPSdk() {
|
||||||
if (PreferenceUtil.getAgreement() && currentProcessName() == packageName) {
|
if (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")
|
||||||
|
|
@ -146,31 +123,31 @@ 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(false)
|
.setCapsule(true)
|
||||||
.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) { success ->
|
DCUniMPSDK.getInstance().initialize(this, config)
|
||||||
uniAppInitialized = success
|
|
||||||
Log.d("UniMP", "onInitFinished: $success")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun currentProcessName(): String? {
|
private fun getProcessName(context: Context): String? {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||||
return getProcessName()
|
return getProcessName()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 旧系统只读取当前进程名,不枚举其他应用的进程。
|
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||||
return runCatching {
|
val runningApps = am.runningAppProcesses ?: return null
|
||||||
File("/proc/self/cmdline").readText().substringBefore('\u0000')
|
for (proInfo in runningApps) {
|
||||||
}.getOrNull()
|
if (proInfo.pid == android.os.Process.myPid()) {
|
||||||
|
return proInfo.processName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
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
|
||||||
|
|
@ -13,22 +14,16 @@ import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.heightIn
|
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
|
||||||
import androidx.compose.foundation.layout.widthIn
|
|
||||||
import androidx.compose.foundation.layout.wrapContentHeight
|
import androidx.compose.foundation.layout.wrapContentHeight
|
||||||
import androidx.compose.foundation.layout.wrapContentSize
|
import androidx.compose.foundation.layout.wrapContentSize
|
||||||
import androidx.compose.foundation.layout.wrapContentWidth
|
import androidx.compose.foundation.layout.wrapContentWidth
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.foundation.text.ClickableText
|
import androidx.compose.foundation.text.ClickableText
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
|
|
@ -44,7 +39,6 @@ import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.scale
|
import androidx.compose.ui.draw.scale
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.layout.ContentScale
|
import androidx.compose.ui.layout.ContentScale
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
|
@ -54,7 +48,6 @@ import androidx.compose.ui.text.TextStyle
|
||||||
import androidx.compose.ui.text.buildAnnotatedString
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextDecoration
|
import androidx.compose.ui.text.style.TextDecoration
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.tooling.preview.Preview
|
import androidx.compose.ui.tooling.preview.Preview
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
@ -65,10 +58,12 @@ import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||||
import com.img.rabbit.bean.response.UniVersionEntity
|
import com.img.rabbit.bean.response.UniVersionEntity
|
||||||
import com.img.rabbit.components.GlobalToast
|
import com.img.rabbit.components.GlobalToast
|
||||||
|
import com.img.rabbit.config.Constants
|
||||||
import com.img.rabbit.config.Constants.agreementUrl
|
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
|
||||||
|
|
@ -77,6 +72,7 @@ import com.img.rabbit.pages.dialog.UpdateDialog
|
||||||
import com.img.rabbit.provider.storage.PreferenceUtil
|
import com.img.rabbit.provider.storage.PreferenceUtil
|
||||||
import com.img.rabbit.utils.AppEventBus
|
import com.img.rabbit.utils.AppEventBus
|
||||||
import com.img.rabbit.utils.AppUpdate
|
import com.img.rabbit.utils.AppUpdate
|
||||||
|
import com.img.rabbit.utils.ChannelUtils
|
||||||
import com.img.rabbit.utils.FileUtils
|
import com.img.rabbit.utils.FileUtils
|
||||||
import com.img.rabbit.utils.GlobalEvent
|
import com.img.rabbit.utils.GlobalEvent
|
||||||
import com.img.rabbit.utils.GlobalEventBus
|
import com.img.rabbit.utils.GlobalEventBus
|
||||||
|
|
@ -89,9 +85,12 @@ import com.img.rabbit.viewmodel.GeneralViewModel
|
||||||
import com.img.rabbit.viewmodel.LoginViewModel
|
import com.img.rabbit.viewmodel.LoginViewModel
|
||||||
import com.img.rabbit.viewmodel.ReportViewModel
|
import com.img.rabbit.viewmodel.ReportViewModel
|
||||||
import com.img.rabbit.viewmodel.SplashViewModel
|
import com.img.rabbit.viewmodel.SplashViewModel
|
||||||
|
import com.umeng.analytics.MobclickAgent
|
||||||
|
import com.umeng.commonsdk.UMConfigure
|
||||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.system.exitProcess
|
||||||
|
|
||||||
class MainActivity : ComponentActivity(), LoadingCallback {
|
class MainActivity : ComponentActivity(), LoadingCallback {
|
||||||
private lateinit var generalViewModel: GeneralViewModel
|
private lateinit var generalViewModel: GeneralViewModel
|
||||||
|
|
@ -106,26 +105,8 @@ class MainActivity : ComponentActivity(), LoadingCallback {
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
|
|
||||||
setContent {
|
setContent {
|
||||||
// 授权前仅渲染原生协议页,不创建会访问 MMKV/网络/微信的业务 ViewModel。
|
|
||||||
var consentAccepted by remember { mutableStateOf(PreferenceUtil.getAgreement()) }
|
|
||||||
if (!consentAccepted) {
|
|
||||||
splashScreen.setKeepOnScreenCondition { false }
|
|
||||||
AppTheme {
|
|
||||||
SplashScreenContent {
|
|
||||||
PrivacyPolicyScreen { accepted ->
|
|
||||||
if (accepted) {
|
|
||||||
PreferenceUtil.saveAgreement(true)
|
|
||||||
(application as BaseApplication).initThirdParty()
|
|
||||||
consentAccepted = true
|
|
||||||
} else {
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return@setContent
|
|
||||||
}
|
|
||||||
val coroutineScope = rememberCoroutineScope()
|
val coroutineScope = rememberCoroutineScope()
|
||||||
|
var showSplash by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val loginViewModel: LoginViewModel = viewModel()
|
val loginViewModel: LoginViewModel = viewModel()
|
||||||
|
|
@ -144,11 +125,9 @@ 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 ->
|
||||||
|
|
@ -163,13 +142,11 @@ 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
|
||||||
}
|
}
|
||||||
// 登录提示
|
// 登录提示
|
||||||
|
|
@ -233,8 +210,6 @@ 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,
|
||||||
|
|
@ -276,7 +251,16 @@ class MainActivity : ComponentActivity(), LoadingCallback {
|
||||||
onRelease = { isSuccess->
|
onRelease = { isSuccess->
|
||||||
if(isSuccess){
|
if(isSuccess){
|
||||||
//资源下载完成后,启动小程序到指定位置
|
//资源下载完成后,启动小程序到指定位置
|
||||||
UniAppUtils.distributeUniMp(context, downloadVersion, reportViewModel, downloadPagePath) {}
|
val uniMpEntity = downloadUniEntity
|
||||||
|
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
|
||||||
|
|
@ -288,11 +272,51 @@ class MainActivity : ComponentActivity(), LoadingCallback {
|
||||||
|
|
||||||
AppTheme {
|
AppTheme {
|
||||||
SplashScreenContent{
|
SplashScreenContent{
|
||||||
if(isLogout){
|
//未同意提示政策弹窗
|
||||||
|
if (!generalViewModel.agreementStatus.value){
|
||||||
|
//同意继续
|
||||||
|
PrivacyPolicyScreen(
|
||||||
|
viewModel = loginViewModel,
|
||||||
|
) { isAllowPrivacyPolicy ->
|
||||||
|
if (isAllowPrivacyPolicy) {
|
||||||
|
generalViewModel.setIsAgreement(true)
|
||||||
|
loginViewModel.setIsPolicyAgreement(true)
|
||||||
|
(applicationContext as BaseApplication).initThirdParty()
|
||||||
|
initUM()
|
||||||
|
showSplash = true
|
||||||
|
} else {
|
||||||
|
// 不同意隐私协议政策,直接退出应用
|
||||||
|
(context as MainActivity).finish()
|
||||||
|
// 强制退出应用进程
|
||||||
|
exitProcess(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
showSplash = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if(showSplash){
|
||||||
|
//val token = PreferenceUtil.getAccessToken()
|
||||||
|
// 未登录,显示登录页
|
||||||
|
//if (token.isNullOrEmpty() && loginViewModel.userConfigResult.value == null) {
|
||||||
|
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 {
|
||||||
|
//已登录,显示主页面
|
||||||
MainScreen(generalViewModel = generalViewModel, loginViewModel = loginViewModel)
|
MainScreen(generalViewModel = generalViewModel, loginViewModel = loginViewModel)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if(showLoginDialog){
|
if(showLoginDialog){
|
||||||
TipsDialog(
|
TipsDialog(
|
||||||
|
|
@ -328,8 +352,8 @@ class MainActivity : ComponentActivity(), LoadingCallback {
|
||||||
}
|
}
|
||||||
|
|
||||||
//UniApp更新提示
|
//UniApp更新提示
|
||||||
val isDownloadingWGT = remember(showUniUpdateDialog) { mutableStateOf(false) }
|
val isDownloadingWGT = mutableStateOf(false)
|
||||||
val progressWGTState = remember(showUniUpdateDialog) { mutableFloatStateOf(0f) }
|
val progressWGTState = mutableFloatStateOf(0f)
|
||||||
if(showUniUpdateDialog){
|
if(showUniUpdateDialog){
|
||||||
updateUniEntity?.let {
|
updateUniEntity?.let {
|
||||||
TipsUniMpDialog(
|
TipsUniMpDialog(
|
||||||
|
|
@ -342,17 +366,11 @@ 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) {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
@ -427,6 +445,15 @@ class MainActivity : ComponentActivity(), LoadingCallback {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化友盟(同意协议的时候,进行一次初始化)
|
||||||
|
*/
|
||||||
|
private fun initUM() {
|
||||||
|
UMConfigure.preInit(applicationContext, Constants.UmengAppkey, ChannelUtils.getChannel(applicationContext))
|
||||||
|
UMConfigure.init(this, Constants.UmengAppkey, ChannelUtils.getChannel(applicationContext), UMConfigure.DEVICE_TYPE_PHONE, "")
|
||||||
|
MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
|
||||||
|
}
|
||||||
|
|
||||||
override fun showLoading() {
|
override fun showLoading() {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
generalViewModel.setLoading(true)
|
generalViewModel.setLoading(true)
|
||||||
|
|
@ -499,39 +526,35 @@ fun SplashScreenContent(
|
||||||
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun PrivacyPolicyScreen(onAgreementChange: (Boolean) -> Unit) {
|
private fun PrivacyPolicyScreen(viewModel: LoginViewModel, onAgreementChange: (Boolean) -> Unit) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
BoxWithConstraints(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier.fillMaxSize()
|
||||||
.fillMaxSize()
|
|
||||||
.background(Color(0xCC000000))
|
|
||||||
.safeDrawingPadding()
|
|
||||||
.padding(horizontal = 24.dp, vertical = 24.dp),
|
|
||||||
contentAlignment = Alignment.Center
|
|
||||||
){
|
){
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.widthIn(max = 400.dp)
|
.fillMaxSize()
|
||||||
.fillMaxWidth()
|
.background(Color(0xCC000000))
|
||||||
.heightIn(max = maxHeight)
|
){
|
||||||
.clip(RoundedCornerShape(26.dp))
|
Box(
|
||||||
.background(Color.White)
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(horizontal = 38.dp, vertical = 213.dp)
|
||||||
|
.align(Alignment.Center)
|
||||||
|
.background(Color.White, shape = RoundedCornerShape(26.dp))
|
||||||
){
|
){
|
||||||
Image(
|
Image(
|
||||||
painter = painterResource(id = R.mipmap.ic_privacy_policy_top_mask),
|
painter = painterResource(id = R.mipmap.ic_privacy_policy_top_mask),
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxSize(),
|
||||||
.height(64.dp),
|
alignment = Alignment.TopCenter
|
||||||
contentScale = ContentScale.FillBounds
|
|
||||||
)
|
)
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.padding(top = 36.dp)
|
||||||
// 内容与按钮使用同一条纵向布局,空间不足时整体滚动。
|
.align(Alignment.TopCenter)
|
||||||
.verticalScroll(rememberScrollState())
|
|
||||||
.padding(start = 24.dp, end = 24.dp, top = 32.dp, bottom = 12.dp)
|
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = "用户协议与隐私政策",
|
text = "用户协议与隐私政策",
|
||||||
|
|
@ -540,8 +563,6 @@ private fun PrivacyPolicyScreen(onAgreementChange: (Boolean) -> Unit) {
|
||||||
.align(Alignment.CenterHorizontally),
|
.align(Alignment.CenterHorizontally),
|
||||||
fontWeight = FontWeight.Normal,
|
fontWeight = FontWeight.Normal,
|
||||||
fontSize = 18.sp,
|
fontSize = 18.sp,
|
||||||
lineHeight = 26.sp,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
color = Color(0xFF1A1A1A)
|
color = Color(0xFF1A1A1A)
|
||||||
)
|
)
|
||||||
Box(
|
Box(
|
||||||
|
|
@ -558,7 +579,7 @@ private fun PrivacyPolicyScreen(onAgreementChange: (Boolean) -> Unit) {
|
||||||
val startIndexPrivacy2 = agreement.lastIndexOf("《隐私政策》")
|
val startIndexPrivacy2 = agreement.lastIndexOf("《隐私政策》")
|
||||||
|
|
||||||
val serviceLength = "《服务协议》".length
|
val serviceLength = "《服务协议》".length
|
||||||
val privacyLength = "《隐私政策》".length
|
val privacyLength = "《服务协议》".length
|
||||||
|
|
||||||
// 高亮显示 "《服务协议》"
|
// 高亮显示 "《服务协议》"
|
||||||
addStyle(
|
addStyle(
|
||||||
|
|
@ -615,11 +636,11 @@ private fun PrivacyPolicyScreen(onAgreementChange: (Boolean) -> Unit) {
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.wrapContentHeight()
|
.wrapContentHeight()
|
||||||
.align(Alignment.CenterHorizontally),
|
.align(Alignment.CenterHorizontally)
|
||||||
|
.padding(horizontal = 12.dp),
|
||||||
style = TextStyle(
|
style = TextStyle(
|
||||||
fontWeight = FontWeight.Normal,
|
fontWeight = FontWeight.Normal,
|
||||||
fontSize = 12.sp,
|
fontSize = 12.sp,
|
||||||
lineHeight = 20.sp,
|
|
||||||
color = Color(0xFF1A1A1A)
|
color = Color(0xFF1A1A1A)
|
||||||
),
|
),
|
||||||
onClick = { offset ->
|
onClick = { offset ->
|
||||||
|
|
@ -637,12 +658,20 @@ private fun PrivacyPolicyScreen(onAgreementChange: (Boolean) -> Unit) {
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
Box(Modifier.height(24.dp))
|
}
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.wrapContentHeight()
|
||||||
|
.align(Alignment.BottomCenter)
|
||||||
|
) {
|
||||||
//同意按钮,用户协议与隐私政策
|
//同意按钮,用户协议与隐私政策
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.wrapContentHeight()
|
.wrapContentHeight()
|
||||||
|
.padding(start = 33.dp, end = 33.dp)
|
||||||
.background(
|
.background(
|
||||||
Color(0xFF252525),
|
Color(0xFF252525),
|
||||||
shape = RoundedCornerShape(359.dp),
|
shape = RoundedCornerShape(359.dp),
|
||||||
|
|
@ -671,6 +700,7 @@ private fun PrivacyPolicyScreen(onAgreementChange: (Boolean) -> Unit) {
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.wrapContentHeight()
|
.wrapContentHeight()
|
||||||
|
.padding(start = 33.dp, end = 33.dp)
|
||||||
.background(
|
.background(
|
||||||
Color(0x00000000),
|
Color(0x00000000),
|
||||||
shape = RoundedCornerShape(359.dp),
|
shape = RoundedCornerShape(359.dp),
|
||||||
|
|
@ -680,6 +710,7 @@ private fun PrivacyPolicyScreen(onAgreementChange: (Boolean) -> Unit) {
|
||||||
interactionSource = remember { MutableInteractionSource() }
|
interactionSource = remember { MutableInteractionSource() }
|
||||||
) {
|
) {
|
||||||
onAgreementChange(false)
|
onAgreementChange(false)
|
||||||
|
viewModel.setIsPolicyAgreement(false)
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
|
|
@ -698,18 +729,10 @@ private fun PrivacyPolicyScreen(onAgreementChange: (Boolean) -> Unit) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Preview(name = "隐私弹窗-小屏", widthDp = 360, heightDp = 640, showBackground = true)
|
|
||||||
@Preview(name = "隐私弹窗-大字体", widthDp = 320, heightDp = 480, fontScale = 1.5f, showBackground = true)
|
|
||||||
@Composable
|
|
||||||
private fun PrivacyPolicyPreview() {
|
|
||||||
MaterialTheme {
|
|
||||||
PrivacyPolicyScreen(onAgreementChange = {})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Preview(showBackground = true)
|
@Preview(showBackground = true)
|
||||||
@Composable
|
@Composable
|
||||||
fun MainScreenPreview() {
|
fun MainScreenPreview() {
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,14 @@
|
||||||
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"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -21,14 +18,6 @@ object ReportType {
|
||||||
}
|
}
|
||||||
|
|
||||||
object ReportKey {
|
object ReportKey {
|
||||||
const val EVENT_CLIENT_HOME_BANNER_CLICK = "client.home.banner.click"
|
|
||||||
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" //页面加载
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,10 @@
|
||||||
package com.img.rabbit.bean.response
|
package com.img.rabbit.bean.response
|
||||||
|
|
||||||
import com.google.gson.annotations.SerializedName
|
import com.google.gson.annotations.SerializedName
|
||||||
import com.google.gson.annotations.JsonAdapter
|
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
class ConfigEntity {
|
class ConfigEntity {
|
||||||
@SerializedName("client.banner.home") //首页轮播图
|
|
||||||
@JsonAdapter(HomeBannerListAdapter::class)
|
|
||||||
var homeBanners: List<HomeBannerEntity?>? = emptyList()
|
|
||||||
@SerializedName("client.version.upgrade") //版本更新
|
@SerializedName("client.version.upgrade") //版本更新
|
||||||
var versionEntity: VersionEntity? = null
|
var versionEntity: VersionEntity? = null
|
||||||
@SerializedName("client.uni.version.upgrade") //小程序模拟器
|
@SerializedName("client.uni.version.upgrade") //小程序模拟器
|
||||||
|
|
@ -17,8 +13,6 @@ 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
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
package com.img.rabbit.bean.response
|
|
||||||
|
|
||||||
import com.google.gson.annotations.SerializedName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
/** client.banner.home,与 flaunt-android 的 HomeBannerBean 字段一致。 */
|
|
||||||
@Serializable
|
|
||||||
data class HomeBannerEntity(
|
|
||||||
@SerializedName(value = "img", alternate = ["icon"])
|
|
||||||
val img: String? = null,
|
|
||||||
val url: String? = null,
|
|
||||||
val type: String? = null,
|
|
||||||
val enable: Boolean? = null,
|
|
||||||
val text: String? = null,
|
|
||||||
) {
|
|
||||||
companion object {
|
|
||||||
fun visibleItems(items: List<HomeBannerEntity?>?): List<HomeBannerEntity> =
|
|
||||||
items.orEmpty().filterNotNull().filter {
|
|
||||||
it.enable == true && !it.img.isNullOrBlank() &&
|
|
||||||
it.type in setOf("wx", "alipay", "app", "web")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
package com.img.rabbit.bean.response
|
|
||||||
|
|
||||||
import com.google.gson.JsonDeserializationContext
|
|
||||||
import com.google.gson.JsonDeserializer
|
|
||||||
import com.google.gson.JsonElement
|
|
||||||
import com.google.gson.JsonParseException
|
|
||||||
import java.lang.reflect.Type
|
|
||||||
|
|
||||||
/** 后端配置兼容单个 banner 对象和 banner 数组。 */
|
|
||||||
class HomeBannerListAdapter : JsonDeserializer<List<HomeBannerEntity?>> {
|
|
||||||
override fun deserialize(
|
|
||||||
json: JsonElement,
|
|
||||||
typeOfT: Type,
|
|
||||||
context: JsonDeserializationContext,
|
|
||||||
): List<HomeBannerEntity?> = when {
|
|
||||||
json.isJsonObject -> listOf(context.deserialize(json, HomeBannerEntity::class.java))
|
|
||||||
json.isJsonArray -> json.asJsonArray.map { item ->
|
|
||||||
context.deserialize<HomeBannerEntity?>(item, HomeBannerEntity::class.java)
|
|
||||||
}
|
|
||||||
json.isJsonNull -> emptyList()
|
|
||||||
else -> throw JsonParseException("client.banner.home must be an object or array")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -14,5 +14,4 @@ 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(),
|
|
||||||
)
|
)
|
||||||
|
|
@ -18,7 +18,6 @@ class UserInfoEntity(
|
||||||
val name: String = "",
|
val name: String = "",
|
||||||
val phone: String = "",
|
val phone: String = "",
|
||||||
val role: String = "",
|
val role: String = "",
|
||||||
val show_contact_menu: Boolean = false,
|
|
||||||
val temp: Boolean = true,
|
val temp: Boolean = true,
|
||||||
val unionid: String = "",
|
val unionid: String = "",
|
||||||
val user_id: String = "",
|
val user_id: String = "",
|
||||||
|
|
|
||||||
|
|
@ -1,124 +0,0 @@
|
||||||
package com.img.rabbit.components
|
|
||||||
|
|
||||||
import androidx.compose.foundation.Image
|
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
|
||||||
import androidx.compose.foundation.interaction.collectIsDraggedAsState
|
|
||||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.aspectRatio
|
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.pager.HorizontalPager
|
|
||||||
import androidx.compose.foundation.pager.rememberPagerState
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.key
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.layout.ContentScale
|
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.lifecycle.Lifecycle
|
|
||||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
|
||||||
import androidx.lifecycle.repeatOnLifecycle
|
|
||||||
import coil3.compose.AsyncImage
|
|
||||||
import com.img.rabbit.R
|
|
||||||
import com.img.rabbit.bean.response.HomeBannerEntity
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.isActive
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun HomeBanner(
|
|
||||||
banners: List<HomeBannerEntity>,
|
|
||||||
onClick: (HomeBannerEntity) -> Unit,
|
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
) {
|
|
||||||
val fallback = painterResource(R.mipmap.ic_home_top_mask)
|
|
||||||
// 保持原顶部图片的宽高比,远程图片加载前后及兜底时布局不跳动。
|
|
||||||
val aspectRatio = fallback.intrinsicSize.width / fallback.intrinsicSize.height
|
|
||||||
if (banners.isEmpty()) {
|
|
||||||
Image(
|
|
||||||
painter = fallback,
|
|
||||||
contentDescription = null,
|
|
||||||
contentScale = ContentScale.Crop,
|
|
||||||
modifier = modifier.fillMaxWidth().aspectRatio(aspectRatio),
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 配置更新时重新建立页码,避免数量减少后仍访问旧页面。
|
|
||||||
key(banners) {
|
|
||||||
val count = banners.size
|
|
||||||
val pageCount = if (count > 1) Int.MAX_VALUE else 1
|
|
||||||
val startPage = if (count > 1) Int.MAX_VALUE / 2 / count * count else 0
|
|
||||||
val pagerState = rememberPagerState(initialPage = startPage) { pageCount }
|
|
||||||
val pressSource = remember { MutableInteractionSource() }
|
|
||||||
val isPressed by pressSource.collectIsPressedAsState()
|
|
||||||
val isDragged by pagerState.interactionSource.collectIsDraggedAsState()
|
|
||||||
val lifecycleOwner = LocalLifecycleOwner.current
|
|
||||||
|
|
||||||
LaunchedEffect(pagerState, lifecycleOwner, isPressed, isDragged) {
|
|
||||||
if (count <= 1 || isPressed || isDragged) return@LaunchedEffect
|
|
||||||
lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
|
|
||||||
while (isActive) {
|
|
||||||
delay(3000)
|
|
||||||
if (!pagerState.isScrollInProgress) {
|
|
||||||
pagerState.animateScrollToPage((pagerState.currentPage + 1) % pageCount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Box(modifier = modifier.fillMaxWidth().aspectRatio(aspectRatio)) {
|
|
||||||
HorizontalPager(
|
|
||||||
state = pagerState,
|
|
||||||
userScrollEnabled = count > 1,
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
|
||||||
) { page ->
|
|
||||||
val item = banners[page % count]
|
|
||||||
AsyncImage(
|
|
||||||
model = item.img,
|
|
||||||
contentDescription = item.text,
|
|
||||||
placeholder = fallback,
|
|
||||||
error = fallback,
|
|
||||||
fallback = fallback,
|
|
||||||
// 等比缩放并居中裁切,图片比例不同时也铺满整个 banner。
|
|
||||||
contentScale = ContentScale.Crop,
|
|
||||||
modifier = Modifier.fillMaxSize().clickable(
|
|
||||||
interactionSource = pressSource,
|
|
||||||
indication = null,
|
|
||||||
) { onClick(item) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (count > 1) {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.align(Alignment.BottomCenter)
|
|
||||||
// 下方内容有 18dp 的圆角重叠区,圆点放在其上方。
|
|
||||||
.padding(bottom = 30.dp)
|
|
||||||
.background(Color.Black.copy(alpha = 0.15f), CircleShape)
|
|
||||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
|
||||||
) {
|
|
||||||
repeat(count) { index ->
|
|
||||||
Box(
|
|
||||||
modifier = Modifier.size(6.dp).background(
|
|
||||||
if (pagerState.currentPage % count == index) Color.White else Color.White.copy(alpha = 0.45f),
|
|
||||||
CircleShape,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -3,7 +3,7 @@ package com.img.rabbit.config
|
||||||
object Constants {
|
object Constants {
|
||||||
const val RELEASE_BASE_URL = "https://jitutu.batiao8.com" //release
|
const val RELEASE_BASE_URL = "https://jitutu.batiao8.com" //release
|
||||||
const val DEBUG_BASE_URL = "https://jitutu.batiao8.com" //debug
|
const val DEBUG_BASE_URL = "https://jitutu.batiao8.com" //debug
|
||||||
const val LOG_REQUEST = "RequestLog"
|
const val LOG_REQUEST = "RabbitRequest"
|
||||||
const val agreementUrl = "https://jitutu.batiao8.com/static/policy-jietutu/user_android.html" //用户协议
|
const val agreementUrl = "https://jitutu.batiao8.com/static/policy-jietutu/user_android.html" //用户协议
|
||||||
const val privacyUrl = "https://jitutu.batiao8.com/static/policy-jietutu/provacy.html"//隐私政策
|
const val privacyUrl = "https://jitutu.batiao8.com/static/policy-jietutu/provacy.html"//隐私政策
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -32,7 +32,6 @@ 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
|
||||||
|
|
@ -93,19 +92,6 @@ 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) {
|
||||||
|
|
@ -118,12 +104,6 @@ fun LoginScreen(navController: NavHostController? = null, generalViewModel: Gene
|
||||||
loginViewModel.isLoginWxAuthor = false
|
loginViewModel.isLoginWxAuthor = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
is WXAuthEvent.AuthFailure -> {
|
|
||||||
if (loginViewModel.isLoginWxAuthor) {
|
|
||||||
loginViewModel.isLoginWxAuthor = false
|
|
||||||
CenterToast.show(event.message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -170,15 +150,7 @@ fun LoginScreen(navController: NavHostController? = null, generalViewModel: Gene
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
) {
|
) {
|
||||||
Box(modifier = Modifier.fillMaxSize()){
|
Box(modifier = Modifier.fillMaxSize()){
|
||||||
if (isPreparingOneKeyLogin) {
|
loginViewModel.setIsPolicyAgreement(false)
|
||||||
Column(
|
|
||||||
modifier = Modifier.align(Alignment.Center),
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally
|
|
||||||
) {
|
|
||||||
CircularProgressIndicator()
|
|
||||||
Text("正在获取本机号码…", modifier = Modifier.padding(top = 16.dp))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
when(loginViewModel.loginScreenType.value){
|
when(loginViewModel.loginScreenType.value){
|
||||||
LoginScreenType.LOGIN_ONE_KEY -> {
|
LoginScreenType.LOGIN_ONE_KEY -> {
|
||||||
//一键登录
|
//一键登录
|
||||||
|
|
@ -214,7 +186,6 @@ fun LoginScreen(navController: NavHostController? = null, generalViewModel: Gene
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
LaunchedEffect(networkStatus) {
|
LaunchedEffect(networkStatus) {
|
||||||
|
|
@ -345,11 +316,7 @@ private fun CaptchaLoginScreen(context: Context, viewModel: LoginViewModel) {
|
||||||
|
|
||||||
BasicTextField(
|
BasicTextField(
|
||||||
value = viewModel.userName.value,
|
value = viewModel.userName.value,
|
||||||
onValueChange = {
|
onValueChange = { viewModel.setUserName(it) },
|
||||||
if (it.length <= 11) {
|
|
||||||
viewModel.setUserName(it)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.background(Color.Transparent)
|
.background(Color.Transparent)
|
||||||
|
|
@ -424,7 +391,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.Number,
|
keyboardType = androidx.compose.ui.text.input.KeyboardType.Text,
|
||||||
imeAction = androidx.compose.ui.text.input.ImeAction.Done
|
imeAction = androidx.compose.ui.text.input.ImeAction.Done
|
||||||
),
|
),
|
||||||
decorationBox = { innerTextField ->
|
decorationBox = { innerTextField ->
|
||||||
|
|
@ -632,18 +599,24 @@ 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
|
||||||
if (preLoginResult == null || !preLoginResult.isValid) {
|
val phoneNumber = viewModel.oneKeyPreLogin?.number ?: ""
|
||||||
LaunchedEffect(Unit) {
|
val operator = preLoginResult.operator//运营商,CM 移动,CT 电信,CU 联通
|
||||||
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
|
||||||
|
|
@ -653,12 +626,15 @@ private fun OneKeyLoginScreen(context: Context, viewModel: LoginViewModel) {
|
||||||
// 使用AndroidView嵌入XML布局
|
// 使用AndroidView嵌入XML布局
|
||||||
@Suppress("COMPOSE_APPLIER_CALL_MISMATCH")
|
@Suppress("COMPOSE_APPLIER_CALL_MISMATCH")
|
||||||
AndroidView(
|
AndroidView(
|
||||||
factory = { viewContext ->
|
factory = { context ->
|
||||||
val view = LayoutInflater.from(viewContext).inflate(
|
LayoutInflater.from(context).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 // 需要回去手机号码
|
||||||
|
|
@ -710,17 +686,18 @@ private fun OneKeyLoginScreen(context: Context, viewModel: LoginViewModel) {
|
||||||
privacyTv = agreementTextView,
|
privacyTv = agreementTextView,
|
||||||
viewModel = viewModel
|
viewModel = viewModel
|
||||||
)
|
)
|
||||||
view
|
// loginButton.setOnClickListener {
|
||||||
},
|
// // 处理登录点击
|
||||||
modifier = Modifier.fillMaxSize(),
|
// oneKeyLogin(
|
||||||
update = { view ->
|
// context = context,
|
||||||
// 只更新勾选状态,避免重绘时重复注册 SDK 登录回调。
|
// numberTv = phoneTextView,
|
||||||
val checkbox = view.findViewById<CheckBox>(R.id.layout_one_key_login_agreement_checkbox)
|
// sloganTv = serviceTextView,
|
||||||
checkbox.setOnCheckedChangeListener(null)
|
// loginBtn = loginButton,
|
||||||
checkbox.isChecked = viewModel.isPolicyAgreement.value
|
// checkBox = checkbox,
|
||||||
checkbox.setOnCheckedChangeListener { _, isChecked ->
|
// privacyTv = agreementTextView,
|
||||||
viewModel.setIsPolicyAgreement(isChecked)
|
// viewModel = viewModel
|
||||||
}
|
// )
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -1210,58 +1187,36 @@ 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?) {
|
||||||
activity.runOnUiThread {
|
|
||||||
loginBtn.isEnabled = true
|
loginBtn.isEnabled = true
|
||||||
if (viewModel.loginScreenType.value != LoginScreenType.LOGIN_ONE_KEY) return@runOnUiThread
|
Log.i("OneKeyLogin", "OneKeyLoginViewModel------onSuccess:$response")
|
||||||
try {
|
try {
|
||||||
val data = JSONObject(response?.msg ?: "{}").getJSONObject("data")
|
val jsonObject = JSONObject(response?.msg?:"{}")
|
||||||
|
val data = jsonObject.getJSONObject("data")
|
||||||
val token = data.getString("token")
|
val token = data.getString("token")
|
||||||
val gyuid = response?.gyuid.orEmpty()
|
viewModel.requestOneKeyLogin(response?.gyuid?:"", token)
|
||||||
if (token.isBlank() || gyuid.isBlank()) {
|
|
||||||
fallbackToCaptcha()
|
|
||||||
} else {
|
|
||||||
viewModel.requestOneKeyLogin(gyuid, token)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w("OneKeyLogin", "一键登录凭证解析失败", e)
|
e.printStackTrace()
|
||||||
fallbackToCaptcha()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onFailed(p0: GYResponse?) {
|
override fun onFailed(p0: GYResponse?) {
|
||||||
fallbackToCaptcha()
|
loginBtn.isEnabled = true
|
||||||
|
Log.e("OneKeyLogin", "OneKeyLoginViewModel------onFailed:$p0")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val eloginActivityParam = EloginActivityParam()
|
val eloginActivityParam = EloginActivityParam()
|
||||||
.setActivity(activity)
|
.setActivity(context as 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 ->
|
||||||
activity.runOnUiThread {
|
|
||||||
loginBtn.isEnabled = true
|
loginBtn.isEnabled = true
|
||||||
if (checkBox.isChecked) {
|
Log.e("OneKeyLogin", "OneKeyLoginViewModel------UIErrorListener.onError:$msg")
|
||||||
fallbackToCaptcha()
|
|
||||||
} else {
|
|
||||||
CenterToast.show("请先同意用户协议和隐私政策")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
.setLoginOnClickListener {
|
.setLoginOnClickListener {
|
||||||
if (!checkBox.isChecked) {
|
if (!checkBox.isChecked) {
|
||||||
|
|
@ -1271,12 +1226,7 @@ private fun oneKeyLogin(
|
||||||
}
|
}
|
||||||
|
|
||||||
// 预先注册登录回调
|
// 预先注册登录回调
|
||||||
try {
|
|
||||||
GYManager.getInstance().eAccountLogin(eloginActivityParam, 5000, gyCallBack)
|
GYManager.getInstance().eAccountLogin(eloginActivityParam, 5000, gyCallBack)
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w("OneKeyLogin", "一键登录授权页初始化失败", e)
|
|
||||||
fallbackToCaptcha()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum class LoginScreenType {
|
enum class LoginScreenType {
|
||||||
|
|
|
||||||
|
|
@ -58,31 +58,9 @@ import com.img.rabbit.viewmodel.LoginViewModel
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
// 定义底部导航的标签页
|
// 定义底部导航的标签页
|
||||||
sealed class TabItem(
|
sealed class TabItem(val title: String, val router:String, val normalIconRes: Int, val selectedIconRes: Int, val normalColor: Color, val selectedColor: Color) {
|
||||||
val title: String,
|
object Home : TabItem("首页", "home", R.mipmap.ic_home_normal, R.mipmap.ic_home_selected, Color(0xFFAAAAAA), Color(0xFF1A1A1A))
|
||||||
val router: String,
|
object Mine : TabItem("我的", "mine", R.mipmap.ic_mine_normal, R.mipmap.ic_mine_selected, Color(0xFFAAAAAA), Color(0xFF1A1A1A))
|
||||||
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)
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -140,14 +118,11 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
|
||||||
bottomBar = {
|
bottomBar = {
|
||||||
if (isNavigationBarVisible) {
|
if (isNavigationBarVisible) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier.navigationBarsPadding()
|
||||||
.background(Color.White)
|
|
||||||
.navigationBarsPadding()
|
|
||||||
) {
|
) {
|
||||||
Box(modifier = Modifier.height(52.dp)) {
|
Box(modifier = Modifier.height(52.dp)) {
|
||||||
NavigationBar(
|
NavigationBar(
|
||||||
containerColor = Color.White,
|
containerColor = Color.White,
|
||||||
tonalElevation = 0.dp,
|
|
||||||
contentColor = Color.Transparent
|
contentColor = Color.Transparent
|
||||||
) {
|
) {
|
||||||
tabItems.forEachIndexed { index, item ->
|
tabItems.forEachIndexed { index, item ->
|
||||||
|
|
@ -170,12 +145,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
label = {
|
label = { Text(item.title, color = if (selectedTab == tabItems[index]) item.selectedColor else item.normalColor) },
|
||||||
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() },
|
||||||
|
|
@ -290,12 +260,10 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
|
||||||
// 添加账号
|
// 添加账号
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
LoginViewModel.JumpLoginType.FROM_LOGOUT.type -> {
|
LoginViewModel.JumpLoginType.FROM_LOGOUT.type -> {
|
||||||
// 退出登录
|
// 退出登录
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> false
|
else -> false
|
||||||
}
|
}
|
||||||
LoginScreen(
|
LoginScreen(
|
||||||
|
|
@ -328,8 +296,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
|
||||||
BindScreen(
|
BindScreen(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
generalViewModel = generalViewModel,
|
generalViewModel = generalViewModel,
|
||||||
bindType = backStackEntry.arguments?.getInt("type")
|
bindType = backStackEntry.arguments?.getInt("type")?:BindViewModel.BindType.FROM_PHONE.type
|
||||||
?: BindViewModel.BindType.FROM_PHONE.type
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -350,7 +317,6 @@ 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 }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,6 @@ 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
|
||||||
|
|
@ -51,8 +50,6 @@ 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
|
||||||
|
|
@ -64,7 +61,7 @@ fun TipsUniMpDialog(
|
||||||
indication = null,
|
indication = null,
|
||||||
interactionSource = remember { MutableInteractionSource() }
|
interactionSource = remember { MutableInteractionSource() }
|
||||||
) {
|
) {
|
||||||
if (!isStartDown.value) onStatusChange(false, true, data)
|
onStatusChange(false, true, data)
|
||||||
},
|
},
|
||||||
verticalArrangement = Arrangement.Center
|
verticalArrangement = Arrangement.Center
|
||||||
){
|
){
|
||||||
|
|
@ -216,8 +213,7 @@ fun TipsUniMpDialog(
|
||||||
interactionSource = remember { MutableInteractionSource() }
|
interactionSource = remember { MutableInteractionSource() }
|
||||||
) {
|
) {
|
||||||
onStatusChange(false, false, data)
|
onStatusChange(false, false, data)
|
||||||
UniAppUtils.reportUpdateChoice(data, true, reportViewModel)
|
UniAppUtils.downloadWGT(context, scope, data){ uniState, filePath, progress ->
|
||||||
UniAppUtils.downloadWGT(context, scope, data, reportViewModel, pagePath){ uniState, _, progress ->
|
|
||||||
when (uniState) {
|
when (uniState) {
|
||||||
UniMpUpdate.DOWNLOAD_START -> {
|
UniMpUpdate.DOWNLOAD_START -> {
|
||||||
//资源开始下载
|
//资源开始下载
|
||||||
|
|
@ -233,7 +229,6 @@ 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 -> {
|
||||||
|
|
|
||||||
|
|
@ -32,6 +32,7 @@ import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableLongStateOf
|
import androidx.compose.runtime.mutableLongStateOf
|
||||||
import androidx.compose.runtime.mutableStateMapOf
|
import androidx.compose.runtime.mutableStateMapOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
|
|
@ -55,21 +56,15 @@ import androidx.navigation.compose.rememberNavController
|
||||||
import coil3.compose.AsyncImage
|
import coil3.compose.AsyncImage
|
||||||
import com.img.rabbit.R
|
import com.img.rabbit.R
|
||||||
import com.img.rabbit.bean.local.UIItemBean
|
import com.img.rabbit.bean.local.UIItemBean
|
||||||
import com.img.rabbit.bean.request.ReportKey
|
|
||||||
import com.img.rabbit.bean.request.ReportRequest
|
|
||||||
import com.img.rabbit.bean.request.ReportType
|
|
||||||
import com.img.rabbit.bean.response.HomeBannerEntity
|
|
||||||
import com.img.rabbit.bean.response.UniVersionEntity
|
import com.img.rabbit.bean.response.UniVersionEntity
|
||||||
import com.img.rabbit.components.CenterToast
|
import com.img.rabbit.components.CenterToast
|
||||||
import com.img.rabbit.components.HomeBanner
|
|
||||||
import com.img.rabbit.pages.LoadingCallback
|
import com.img.rabbit.pages.LoadingCallback
|
||||||
|
import com.img.rabbit.provider.storage.PreferenceUtil
|
||||||
import com.img.rabbit.route.ScreenRoute
|
import com.img.rabbit.route.ScreenRoute
|
||||||
import com.img.rabbit.route.HomeBannerRoutes
|
|
||||||
import com.img.rabbit.utils.GlobalEvent
|
import com.img.rabbit.utils.GlobalEvent
|
||||||
import com.img.rabbit.utils.GlobalEventBus
|
import com.img.rabbit.utils.GlobalEventBus
|
||||||
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.utils.UrlLinkUtils
|
|
||||||
import com.img.rabbit.viewmodel.GeneralViewModel
|
import com.img.rabbit.viewmodel.GeneralViewModel
|
||||||
import com.img.rabbit.viewmodel.LoginViewModel
|
import com.img.rabbit.viewmodel.LoginViewModel
|
||||||
import com.img.rabbit.viewmodel.ReportViewModel
|
import com.img.rabbit.viewmodel.ReportViewModel
|
||||||
|
|
@ -77,7 +72,6 @@ import io.dcloud.feature.sdk.DCUniMPSDK
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
|
||||||
import kotlin.collections.chunked
|
import kotlin.collections.chunked
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -159,11 +153,13 @@ fun HomeScreen(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val userConfig = loginViewModel.userConfig.value?.config
|
var homeIconConfig by remember { mutableStateOf(PreferenceUtil.getUserConfig()?.config?.homeIconEntity) }
|
||||||
val homeIconConfig = userConfig?.homeIconEntity
|
var uniVersionConfig by remember { mutableStateOf(PreferenceUtil.getUserConfig()?.config?.uniVersionEntity) }
|
||||||
val uniVersionConfig = userConfig?.uniVersionEntity
|
LaunchedEffect(loginViewModel.userConfigResult.value) {
|
||||||
val homeBanners = remember(userConfig?.homeBanners) {
|
if(loginViewModel.userConfigResult.value != null){
|
||||||
HomeBannerEntity.visibleItems(userConfig?.homeBanners)
|
homeIconConfig = PreferenceUtil.getUserConfig()?.config?.homeIconEntity
|
||||||
|
uniVersionConfig = PreferenceUtil.getUserConfig()?.config?.uniVersionEntity
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
|
|
@ -181,59 +177,13 @@ fun HomeScreen(
|
||||||
shape = RoundedCornerShape(topStart = 18.dp, topEnd = 18.dp)
|
shape = RoundedCornerShape(topStart = 18.dp, topEnd = 18.dp)
|
||||||
)
|
)
|
||||||
){
|
){
|
||||||
// 顶部轮播,无配置和加载失败时使用原顶部图片兜底。
|
// 顶部mask
|
||||||
item(key = "home_banner") {
|
item {
|
||||||
HomeBanner(
|
Image(
|
||||||
banners = homeBanners,
|
painter = painterResource(id = R.mipmap.ic_home_top_mask),
|
||||||
onClick = { banner ->
|
contentDescription = null,
|
||||||
val type = banner.type.orEmpty()
|
contentScale = ContentScale.FillWidth,
|
||||||
val url = banner.url.orEmpty()
|
modifier = Modifier.fillMaxWidth()
|
||||||
reportViewModel.requestReport(ReportRequest(
|
|
||||||
type = ReportType.CLICK,
|
|
||||||
key = ReportKey.EVENT_CLIENT_HOME_BANNER_CLICK,
|
|
||||||
value = type,
|
|
||||||
extra = url,
|
|
||||||
))
|
|
||||||
when (type) {
|
|
||||||
"wx", "alipay" -> {
|
|
||||||
if (loginViewModel.requiredLogin()) {
|
|
||||||
val version = uniVersionConfig?.firstOrNull { it.unimp_type == type }
|
|
||||||
if (version == null) {
|
|
||||||
CenterToast.show("功能暂不可用,请稍后重试")
|
|
||||||
} else {
|
|
||||||
dealUniMpDownloadLaunch(
|
|
||||||
context, scope, version, progressPair,
|
|
||||||
reportViewModel, loadingCallback,
|
|
||||||
pagePath = url.takeIf { it.isNotBlank() },
|
|
||||||
itemName = banner.text?.takeIf { it.isNotBlank() } ?: "home",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"web" -> {
|
|
||||||
if (url.isNotBlank()) {
|
|
||||||
if (url.toHttpUrlOrNull() != null) {
|
|
||||||
UrlLinkUtils.openAgreement(context, banner.text.orEmpty(), url)
|
|
||||||
} else {
|
|
||||||
CenterToast.show("链接暂不可用")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"app" -> {
|
|
||||||
if (url.isNotBlank()) {
|
|
||||||
val route = HomeBannerRoutes.resolve(url)
|
|
||||||
if (route == null) {
|
|
||||||
CenterToast.show("功能暂不可用,请稍后重试")
|
|
||||||
} else {
|
|
||||||
generalViewModel.setNavigationBarVisible(
|
|
||||||
route == ScreenRoute.Home.route || route == ScreenRoute.Mine.route
|
|
||||||
)
|
|
||||||
navController.navigate(route) { launchSingleTop = true }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
|
|
@ -249,7 +199,7 @@ fun HomeScreen(
|
||||||
}
|
}
|
||||||
|
|
||||||
// 当配置开启模拟器时,展示模拟器部分
|
// 当配置开启模拟器时,展示模拟器部分
|
||||||
if(userConfig?.isUniMpOpen == true){
|
if(PreferenceUtil.getUserConfig()?.config?.isUniMpOpen?:false){
|
||||||
//模拟器部分,大于9时,每排展示3个,否则每排展示4个
|
//模拟器部分,大于9时,每排展示3个,否则每排展示4个
|
||||||
val columnsCount = if((homeIconConfig?.size?:0) >= 9){ 3 }else{ 4 }
|
val columnsCount = if((homeIconConfig?.size?:0) >= 9){ 3 }else{ 4 }
|
||||||
val rows = homeIconConfig?.chunked(columnsCount)?:emptyList()
|
val rows = homeIconConfig?.chunked(columnsCount)?:emptyList()
|
||||||
|
|
@ -319,7 +269,7 @@ fun HomeScreen(
|
||||||
)
|
)
|
||||||
|
|
||||||
//下载完成前显示
|
//下载完成前显示
|
||||||
if((progressPair[uniMpId]?:-1f) >= 0f && (progressPair[uniMpId]?:-1f) < 1f){
|
if((progressPair[uniMpId]?:0f) > 0f && (progressPair[uniMpId]?:0f) < 1f){
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
|
|
@ -393,7 +343,7 @@ fun HomeScreen(
|
||||||
)
|
)
|
||||||
|
|
||||||
//下载完成前显示
|
//下载完成前显示
|
||||||
if((progressPair[uniMpId]?:-1f) >= 0f && (progressPair[uniMpId]?:-1f) < 1f){
|
if((progressPair[uniMpId]?:0f) > 0f && (progressPair[uniMpId]?:0f) < 1f){
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
|
|
@ -456,16 +406,23 @@ fun HomeScreen(
|
||||||
}
|
}
|
||||||
|
|
||||||
val uniVersion =
|
val uniVersion =
|
||||||
uniVersionConfig?.firstOrNull { it.unimp_type == item.type }
|
PreferenceUtil.getUserConfig()?.config?.uniVersionEntity?.firstOrNull { it.unimp_type == item.type }
|
||||||
if(uniVersion == null){
|
if(uniVersion == null){
|
||||||
CenterToast.show("无可用资源...")
|
CenterToast.show("无可用资源...")
|
||||||
return@clickable
|
return@clickable
|
||||||
}
|
}
|
||||||
dealUniMpDownloadLaunch(
|
val uniMpId = uniVersion.unimp_id
|
||||||
context, scope, uniVersion, progressPair,
|
UniAppUtils.currentUniMpJumpPatch = item.url
|
||||||
reportViewModel, loadingCallback,
|
val wgtExists = UniAppUtils.wgtIsExists(uniMpId)
|
||||||
pagePath = item.url, itemName = item.text
|
if(!wgtExists){
|
||||||
)
|
//是否下载
|
||||||
|
scope.launch {
|
||||||
|
GlobalEventBus.emit(
|
||||||
|
GlobalEvent.ShowUniDownloadNotify(uniVersion))
|
||||||
|
}
|
||||||
|
}else {
|
||||||
|
UniAppUtils.startUniMpPage(context = context, uniMpId = uniMpId, uniMpType = item.type, pagePath = item.url, reportViewModel = reportViewModel)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
Column {
|
Column {
|
||||||
|
|
@ -808,32 +765,17 @@ 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) }
|
||||||
|
|
@ -876,14 +818,15 @@ 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, pagePath))
|
GlobalEvent.ShowUniUpdateNotify(uniMp))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
loadingCallback?.showLoading()
|
loadingCallback?.showLoading()
|
||||||
//启动uni小程序(1、直接启动;2、释放并启动)
|
//启动uni小程序(1、直接启动;2、释放并启动)
|
||||||
UniAppUtils.distributeUniMp(context, uniMp, reportViewModel, pagePath) {
|
UniAppUtils.distributeUniMp(context, uniMp, reportViewModel) {
|
||||||
loadingCallback?.hideLoading()
|
loadingCallback?.hideLoading()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,8 +22,10 @@ import androidx.compose.foundation.layout.wrapContentSize
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableLongStateOf
|
import androidx.compose.runtime.mutableLongStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
|
|
@ -55,6 +57,7 @@ import com.img.rabbit.utils.GlobalEventBus
|
||||||
import com.img.rabbit.viewmodel.GeneralViewModel
|
import com.img.rabbit.viewmodel.GeneralViewModel
|
||||||
import com.img.rabbit.viewmodel.LoginViewModel
|
import com.img.rabbit.viewmodel.LoginViewModel
|
||||||
import com.img.rabbit.viewmodel.MineViewModel
|
import com.img.rabbit.viewmodel.MineViewModel
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -72,7 +75,7 @@ fun MineScreen(
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
//用户数据
|
//用户数据
|
||||||
val userInfo by loginViewModel.userInfo
|
var userInfo by remember { mutableStateOf(PreferenceUtil.getUserInfo()) }
|
||||||
// 获取当前路由状态
|
// 获取当前路由状态
|
||||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||||
val currentRoute = navBackStackEntry?.destination?.route
|
val currentRoute = navBackStackEntry?.destination?.route
|
||||||
|
|
@ -89,6 +92,15 @@ fun MineScreen(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(loginViewModel.userInfoResult.value) {
|
||||||
|
if(loginViewModel.userInfoResult.value != null){
|
||||||
|
// 等待200ms,确保用户配置已经刷新
|
||||||
|
delay(200)
|
||||||
|
userInfo = PreferenceUtil.getUserInfo()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
|
|
@ -390,7 +402,6 @@ fun MineScreen(
|
||||||
Color(0x4DBBBBBB)
|
Color(0x4DBBBBBB)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if(userInfo?.show_contact_menu == true){
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
|
|
@ -399,7 +410,11 @@ fun MineScreen(
|
||||||
indication = null,
|
indication = null,
|
||||||
interactionSource = remember { MutableInteractionSource() }
|
interactionSource = remember { MutableInteractionSource() }
|
||||||
) {
|
) {
|
||||||
|
if (!generalViewModel.api.isWXAppInstalled) {
|
||||||
|
CenterToast.show("未安装微信客户端")
|
||||||
|
}else if(userInfo != null){
|
||||||
viewModel.requestServiceLink(generalViewModel.api)
|
viewModel.requestServiceLink(generalViewModel.api)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically
|
||||||
) {
|
) {
|
||||||
|
|
@ -443,7 +458,6 @@ fun MineScreen(
|
||||||
Color(0x4DBBBBBB)
|
Color(0x4DBBBBBB)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,7 @@ import coil3.compose.AsyncImage
|
||||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||||
import com.google.accompanist.permissions.isGranted
|
import com.google.accompanist.permissions.isGranted
|
||||||
import com.google.accompanist.permissions.rememberPermissionState
|
import com.google.accompanist.permissions.rememberPermissionState
|
||||||
|
import com.google.accompanist.permissions.shouldShowRationale
|
||||||
import com.img.rabbit.R
|
import com.img.rabbit.R
|
||||||
import com.img.rabbit.bean.local.ClothingBean
|
import com.img.rabbit.bean.local.ClothingBean
|
||||||
import com.img.rabbit.bean.local.HairstyleBean
|
import com.img.rabbit.bean.local.HairstyleBean
|
||||||
|
|
@ -101,10 +102,7 @@ import java.util.Date
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import com.img.rabbit.utils.PhotoCutter
|
import com.img.rabbit.utils.PhotoCutter
|
||||||
import com.img.rabbit.viewmodel.CutoutViewModel
|
import com.img.rabbit.viewmodel.CutoutViewModel
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
|
|
||||||
|
|
||||||
// 建议的状态数据结构
|
// 建议的状态数据结构
|
||||||
|
|
@ -148,10 +146,8 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
|
||||||
val coroutineScope = rememberCoroutineScope()
|
val coroutineScope = rememberCoroutineScope()
|
||||||
// 抠图加载中状态
|
// 抠图加载中状态
|
||||||
val isLoading = remember { mutableStateOf(false) }
|
val isLoading = remember { mutableStateOf(false) }
|
||||||
var isSaving by remember { mutableStateOf(false) }
|
|
||||||
var recordedImage by remember { mutableStateOf<Bitmap?>(null) }
|
|
||||||
|
|
||||||
val widthParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("width") ?: 25f
|
val widthParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("width") ?: 23f
|
||||||
val heightParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("height") ?: 35f
|
val heightParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("height") ?: 35f
|
||||||
|
|
||||||
//显示服装和发型
|
//显示服装和发型
|
||||||
|
|
@ -192,7 +188,7 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
|
||||||
// 当前选中的发型
|
// 当前选中的发型
|
||||||
val selectedHairstyle = remember { mutableStateOf(hairstyleForFemales.getOrNull(0)) }
|
val selectedHairstyle = remember { mutableStateOf(hairstyleForFemales.getOrNull(0)) }
|
||||||
// 当前选中的尺寸
|
// 当前选中的尺寸
|
||||||
val selectedSize = remember { mutableStateOf(resizes.firstOrNull { it.width == widthParam && it.height == heightParam } ?: resizes.first()) }
|
val selectedSize = remember { mutableStateOf(resizes.first { it.width == widthParam && it.height == heightParam }) }
|
||||||
|
|
||||||
|
|
||||||
val storagePermissionState = rememberPermissionState(
|
val storagePermissionState = rememberPermissionState(
|
||||||
|
|
@ -211,8 +207,6 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
|
||||||
) { uri ->
|
) { uri ->
|
||||||
uri?.let {
|
uri?.let {
|
||||||
selectedImageUri.value = it
|
selectedImageUri.value = it
|
||||||
cutoutResultBitmap.value = null
|
|
||||||
recordedImage = null
|
|
||||||
isLoading.value = true
|
isLoading.value = true
|
||||||
// 执行抠图操作
|
// 执行抠图操作
|
||||||
if(isLoadingCutoutMethodFromService){
|
if(isLoadingCutoutMethodFromService){
|
||||||
|
|
@ -296,47 +290,54 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
|
||||||
.navigationBarsPadding()
|
.navigationBarsPadding()
|
||||||
) {
|
) {
|
||||||
TitleBar(navController = navController, paddingValues = it, title = "", showSave = true){
|
TitleBar(navController = navController, paddingValues = it, title = "", showSave = true){
|
||||||
if (isSaving) return@TitleBar
|
// 保存图片
|
||||||
if (isLoading.value || cutoutResultBitmap.value == null) {
|
|
||||||
CenterToast.show("请等待抠图完成后再保存")
|
|
||||||
return@TitleBar
|
|
||||||
}
|
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && !storagePermissionState.status.isGranted) {
|
|
||||||
storagePermissionState.launchPermissionRequest()
|
|
||||||
return@TitleBar
|
|
||||||
}
|
|
||||||
// Receiving the result does not mean Compose has recorded the new canvas yet.
|
|
||||||
if (recordedImage !== cutoutResultBitmap.value || graphicsLayer.isReleased ||
|
|
||||||
graphicsLayer.size.width <= 0 || graphicsLayer.size.height <= 0) {
|
|
||||||
CenterToast.show("图片尚未绘制完成,请稍后保存")
|
|
||||||
return@TitleBar
|
|
||||||
}
|
|
||||||
isSaving = true
|
|
||||||
coroutineScope.launch {
|
coroutineScope.launch {
|
||||||
try {
|
// 从 Layer 捕获 Bitmap
|
||||||
val bitmap = graphicsLayer.toImageBitmap().asAndroidBitmap()
|
val bitmap = graphicsLayer.toImageBitmap().asAndroidBitmap()
|
||||||
try {
|
// 保存图片到系统相册(图片已按比例裁剪)
|
||||||
val result = withContext(Dispatchers.IO) {
|
/*
|
||||||
var result: Pair<String, Boolean> = "" to false
|
saveCanvasToGallery(context, bitmap, ExportFormat.JPG){fileName, isSuccess ->
|
||||||
saveCanvasToGallery(context, bitmap, ExportFormat.JPG) { filename, success ->
|
val tips = if(isSuccess){ "已保存为: $fileName" }else{ "保存失败" }
|
||||||
result = filename to success
|
CenterToast.show(tips)
|
||||||
}
|
}
|
||||||
result
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
// 保存图片到系统相册(指定尺寸,如果targetWidth与targetHeight比原始值小太多会导致图片模糊)
|
||||||
|
saveCanvasToGallery(context, bitmap, ExportFormat.JPG, selectedSize.value.width.toInt(), selectedSize.value.height.toInt()){fileName, isSuccess ->
|
||||||
|
if(isSuccess){
|
||||||
|
Toast.makeText(context, "已保存为: $fileName", Toast.LENGTH_SHORT).show()
|
||||||
|
}else{
|
||||||
|
Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
// 保存图片到系统相册(图片已按比例裁剪)
|
||||||
|
saveCanvasToGallery(context, bitmap, ExportFormat.JPG){fileName, isSuccess ->
|
||||||
|
val tips = if(isSuccess){ "已保存为: $fileName" }else{ "保存失败" }
|
||||||
|
CenterToast.show(tips)
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
when {
|
||||||
|
// 情况 A:已获得权限
|
||||||
|
storagePermissionState.status.isGranted -> {
|
||||||
|
// 保存图片到系统相册(图片已按比例裁剪)
|
||||||
|
saveCanvasToGallery(context, bitmap, ExportFormat.JPG){fileName, isSuccess ->
|
||||||
|
val tips = if(isSuccess){ "已保存为: $fileName" }else{ "保存失败" }
|
||||||
|
CenterToast.show(tips)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 情况 B:需要向用户解释(之前拒绝过,但未勾选“不再询问”)
|
||||||
|
storagePermissionState.status.shouldShowRationale -> {
|
||||||
|
storagePermissionState.launchPermissionRequest()
|
||||||
|
}
|
||||||
|
// 情况 C:从未请求过权限或已被彻底拒绝
|
||||||
|
else -> {
|
||||||
|
storagePermissionState.launchPermissionRequest()
|
||||||
}
|
}
|
||||||
CenterToast.show(if (result.second) "已保存为: ${result.first}" else "保存失败,请重试")
|
|
||||||
} finally {
|
|
||||||
bitmap.recycle()
|
|
||||||
}
|
}
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e("CutoutScreen", "保存抠图结果失败", e)
|
|
||||||
CenterToast.show("保存失败,请稍后重试")
|
|
||||||
} catch (e: OutOfMemoryError) {
|
|
||||||
Log.e("CutoutScreen", "保存图片时内存不足", e)
|
|
||||||
CenterToast.show("内存不足,请稍后重试")
|
|
||||||
} finally {
|
|
||||||
isSaving = false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -397,7 +398,6 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
|
||||||
graphicsLayer.record {
|
graphicsLayer.record {
|
||||||
this@drawWithContent.drawContent()
|
this@drawWithContent.drawContent()
|
||||||
}
|
}
|
||||||
recordedImage = cutoutResultBitmap.value
|
|
||||||
drawLayer(graphicsLayer)
|
drawLayer(graphicsLayer)
|
||||||
}
|
}
|
||||||
.clipToBounds()
|
.clipToBounds()
|
||||||
|
|
|
||||||
|
|
@ -197,7 +197,7 @@ fun AccountBindScreen(navController: NavHostController, viewModel: AccountBindVi
|
||||||
indication = null,
|
indication = null,
|
||||||
interactionSource = remember { MutableInteractionSource() }
|
interactionSource = remember { MutableInteractionSource() }
|
||||||
) {
|
) {
|
||||||
// 跳转绑定或解绑微信
|
//TODO 跳转绑定或解绑微信
|
||||||
if (userInfo?.weixinAppId.isNullOrEmpty()) {
|
if (userInfo?.weixinAppId.isNullOrEmpty()) {
|
||||||
navController.navigate("bind?type=${BindViewModel.BindType.FROM_WX.type}")
|
navController.navigate("bind?type=${BindViewModel.BindType.FROM_WX.type}")
|
||||||
} else {
|
} else {
|
||||||
|
|
|
||||||
|
|
@ -98,12 +98,6 @@ fun BindScreen(navController: NavHostController, viewModel: BindViewModel = view
|
||||||
viewModel.isBindWxAuthor = false
|
viewModel.isBindWxAuthor = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
is WXAuthEvent.AuthFailure -> {
|
|
||||||
if (viewModel.isBindWxAuthor) {
|
|
||||||
viewModel.isBindWxAuthor = false
|
|
||||||
CenterToast.show(event.message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
package com.img.rabbit.provider
|
|
||||||
|
|
||||||
import android.content.ContentProvider
|
|
||||||
import android.content.ContentValues
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.pm.ProviderInfo
|
|
||||||
import android.database.Cursor
|
|
||||||
import android.net.Uri
|
|
||||||
import android.os.Bundle
|
|
||||||
import com.getui.gtc.base.GtcProvider
|
|
||||||
import com.img.rabbit.provider.storage.PrivacyConsentStore
|
|
||||||
|
|
||||||
/** 保留个推的进程通信地址,但在授权前不创建 SDK Provider。 */
|
|
||||||
class ConsentGtcProvider : ContentProvider() {
|
|
||||||
private var delegate: ContentProvider? = null
|
|
||||||
private lateinit var providerInfo: ProviderInfo
|
|
||||||
|
|
||||||
override fun attachInfo(context: Context, info: ProviderInfo) {
|
|
||||||
providerInfo = info
|
|
||||||
super.attachInfo(context, info)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreate(): Boolean = true
|
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
private fun initialize(): ContentProvider? {
|
|
||||||
if (!PrivacyConsentStore.isAccepted()) return null
|
|
||||||
return delegate ?: GtcProvider().also {
|
|
||||||
it.attachInfo(requireNotNull(context), providerInfo)
|
|
||||||
delegate = it
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun call(method: String, arg: String?, extras: Bundle?): Bundle? {
|
|
||||||
val provider = initialize() ?: return null
|
|
||||||
return if (method == INITIALIZE) Bundle() else provider.call(method, arg, extras)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
|
|
||||||
selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
|
|
||||||
override fun getType(uri: Uri): String? = null
|
|
||||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
|
||||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
|
||||||
override fun update(uri: Uri, values: ContentValues?, selection: String?,
|
|
||||||
selectionArgs: Array<out String>?): Int = 0
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val INITIALIZE = "rabbit.initializeAfterConsent"
|
|
||||||
|
|
||||||
fun initializeAfterConsent(context: Context) {
|
|
||||||
if (!PrivacyConsentStore.isAccepted()) return
|
|
||||||
context.contentResolver.call(
|
|
||||||
Uri.parse("content://${context.packageName}.getui.gtc.provider"),
|
|
||||||
INITIALIZE, null, null
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -2,16 +2,14 @@
|
||||||
|
|
||||||
package com.img.rabbit.provider.api
|
package com.img.rabbit.provider.api
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import com.batiao.batiaosdk.SignInterceptor
|
|
||||||
import com.img.rabbit.BuildConfig
|
import com.img.rabbit.BuildConfig
|
||||||
import com.img.rabbit.config.Constants
|
import com.img.rabbit.config.Constants
|
||||||
import com.img.rabbit.provider.utils.HeaderInterceptor
|
import com.img.rabbit.provider.utils.HeaderInterceptor
|
||||||
|
import com.img.rabbit.provider.utils.RequestInterceptor
|
||||||
import com.img.rabbit.provider.utils.ResponseInterceptor
|
import com.img.rabbit.provider.utils.ResponseInterceptor
|
||||||
import com.img.rabbit.provider.utils.getUnsafeOkHttpClient
|
import com.img.rabbit.provider.utils.getUnsafeOkHttpClient
|
||||||
import com.img.rabbit.viewmodel.`interface`.ServiceVo
|
import com.img.rabbit.viewmodel.`interface`.ServiceVo
|
||||||
import okhttp3.OkHttpClient
|
import okhttp3.OkHttpClient
|
||||||
import okhttp3.logging.HttpLoggingInterceptor
|
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
import retrofit2.converter.gson.GsonConverterFactory
|
import retrofit2.converter.gson.GsonConverterFactory
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
@ -35,14 +33,12 @@ object ApiManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!::retrofit.isInitialized) {
|
if (!::retrofit.isInitialized) {
|
||||||
// 仅业务 API 使用 Batiao 签名和解密,资源下载保持原始 URL。
|
val client = OkHttpClient().newBuilder()
|
||||||
val client = OkHttpClient.Builder()
|
|
||||||
.connectTimeout(10, TimeUnit.SECONDS)
|
.connectTimeout(10, TimeUnit.SECONDS)
|
||||||
.readTimeout(20, TimeUnit.SECONDS)
|
.readTimeout(20, TimeUnit.SECONDS)
|
||||||
.writeTimeout(20, TimeUnit.SECONDS)
|
.writeTimeout(20, TimeUnit.SECONDS)
|
||||||
|
.addInterceptor(RequestInterceptor())
|
||||||
.addInterceptor(HeaderInterceptor())
|
.addInterceptor(HeaderInterceptor())
|
||||||
.addDebugRequestLogging()
|
|
||||||
.addInterceptor(SignInterceptor)
|
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
retrofit = Retrofit.Builder()
|
retrofit = Retrofit.Builder()
|
||||||
|
|
@ -58,9 +54,8 @@ object ApiManager {
|
||||||
.readTimeout(20, TimeUnit.SECONDS)
|
.readTimeout(20, TimeUnit.SECONDS)
|
||||||
.writeTimeout(20, TimeUnit.SECONDS)
|
.writeTimeout(20, TimeUnit.SECONDS)
|
||||||
.addInterceptor(HeaderInterceptor())
|
.addInterceptor(HeaderInterceptor())
|
||||||
|
.addInterceptor(RequestInterceptor())
|
||||||
.addInterceptor(ResponseInterceptor())
|
.addInterceptor(ResponseInterceptor())
|
||||||
.addDebugRequestLogging()
|
|
||||||
.addInterceptor(SignInterceptor)
|
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
unsafeRetrofit = Retrofit.Builder()
|
unsafeRetrofit = Retrofit.Builder()
|
||||||
|
|
@ -75,19 +70,6 @@ object ApiManager {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun OkHttpClient.Builder.addDebugRequestLogging(): OkHttpClient.Builder = apply {
|
|
||||||
if (BuildConfig.DEBUG) {
|
|
||||||
// 放在签名拦截器外侧,以记录 SDK 解密后的响应。
|
|
||||||
addInterceptor(HttpLoggingInterceptor { message ->
|
|
||||||
message.chunked(1000).forEach { chunk ->
|
|
||||||
Log.d(Constants.LOG_REQUEST, chunk)
|
|
||||||
}
|
|
||||||
}.apply {
|
|
||||||
level = HttpLoggingInterceptor.Level.BODY
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 添加重新初始化方法,用于在baseUrl改变时调用
|
// 添加重新初始化方法,用于在baseUrl改变时调用
|
||||||
fun reinitialize() {
|
fun reinitialize() {
|
||||||
// 重置所有实例,使其在下一次访问时重新初始化
|
// 重置所有实例,使其在下一次访问时重新初始化
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,18 @@
|
||||||
package com.img.rabbit.provider.storage
|
package com.img.rabbit.provider.storage
|
||||||
|
|
||||||
|
import android.text.TextUtils
|
||||||
import com.google.gson.Gson
|
import com.google.gson.Gson
|
||||||
import com.google.gson.GsonBuilder
|
import com.google.gson.GsonBuilder
|
||||||
import com.img.rabbit.bean.local.UniMpVersionBean
|
import com.img.rabbit.bean.local.UniMpVersionBean
|
||||||
import com.img.rabbit.bean.response.UserConfigEntity
|
import com.img.rabbit.bean.response.UserConfigEntity
|
||||||
import com.img.rabbit.bean.response.LoginInfoEntity
|
import com.img.rabbit.bean.response.LoginInfoEntity
|
||||||
import com.img.rabbit.bean.response.UserInfoEntity
|
import com.img.rabbit.bean.response.UserInfoEntity
|
||||||
|
import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext
|
||||||
|
import com.img.rabbit.utils.MMKVUtils
|
||||||
import com.img.rabbit.utils.MMKVUtils.mmkv
|
import com.img.rabbit.utils.MMKVUtils.mmkv
|
||||||
|
import com.img.rabbit.utils.appwalle.ChannelReader
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SharedPreferences工具类,用于简化数据持久化操作
|
* SharedPreferences工具类,用于简化数据持久化操作
|
||||||
|
|
@ -22,6 +27,7 @@ object PreferenceUtil {
|
||||||
private const val KEY_USER_CONFIG = "user_config"
|
private const val KEY_USER_CONFIG = "user_config"
|
||||||
private const val KEY_WX_CODE = "wx_code"
|
private const val KEY_WX_CODE = "wx_code"
|
||||||
private const val KEY_USER_INFO = "user_info"
|
private const val KEY_USER_INFO = "user_info"
|
||||||
|
private const val KEY_AGREEMENT = "agreement"
|
||||||
private const val KEY_WGT_VERSION = "uni_wgt_version"
|
private const val KEY_WGT_VERSION = "uni_wgt_version"
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -32,7 +38,7 @@ object PreferenceUtil {
|
||||||
|
|
||||||
|
|
||||||
// Gson实例
|
// Gson实例
|
||||||
private val gson: Gson by lazy { GsonBuilder().create() }
|
private val gson: Gson = GsonBuilder().create()
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -68,11 +74,11 @@ object PreferenceUtil {
|
||||||
|
|
||||||
|
|
||||||
fun saveAgreement(agreement: Boolean) {
|
fun saveAgreement(agreement: Boolean) {
|
||||||
PrivacyConsentStore.setAccepted(agreement)
|
mmkv.putBoolean(KEY_AGREEMENT, agreement)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getAgreement(): Boolean {
|
fun getAgreement(): Boolean {
|
||||||
return PrivacyConsentStore.isAccepted()
|
return mmkv.decodeBool(KEY_AGREEMENT, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun saveUserConfig(config: UserConfigEntity?) {
|
fun saveUserConfig(config: UserConfigEntity?) {
|
||||||
|
|
@ -131,7 +137,7 @@ object PreferenceUtil {
|
||||||
|
|
||||||
fun saveUserInfo(userInfoEntity: UserInfoEntity?) {
|
fun saveUserInfo(userInfoEntity: UserInfoEntity?) {
|
||||||
if(userInfoEntity == null){
|
if(userInfoEntity == null){
|
||||||
mmkv.remove(KEY_USER_INFO)
|
mmkv.encode(KEY_USER_INFO, gson.toJson("{}"))
|
||||||
}else{
|
}else{
|
||||||
mmkv.encode(KEY_USER_INFO, gson.toJson(userInfoEntity))
|
mmkv.encode(KEY_USER_INFO, gson.toJson(userInfoEntity))
|
||||||
}
|
}
|
||||||
|
|
@ -139,8 +145,7 @@ object PreferenceUtil {
|
||||||
|
|
||||||
fun getUserInfo(): UserInfoEntity? {
|
fun getUserInfo(): UserInfoEntity? {
|
||||||
return try {
|
return try {
|
||||||
gson.fromJson(mmkv.decodeString(KEY_USER_INFO, null), UserInfoEntity::class.java)
|
gson.fromJson(mmkv.decodeString(KEY_USER_INFO, "{}"), UserInfoEntity::class.java)
|
||||||
?.takeIf { !it.user_id.isNullOrBlank() }
|
|
||||||
}catch (e: Exception){
|
}catch (e: Exception){
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
|
|
@ -208,6 +213,5 @@ object PreferenceUtil {
|
||||||
*/
|
*/
|
||||||
fun clearAll() {
|
fun clearAll() {
|
||||||
mmkv.clearAll()
|
mmkv.clearAll()
|
||||||
PrivacyConsentStore.setAccepted(false)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
package com.img.rabbit.provider.storage
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.SharedPreferences
|
|
||||||
|
|
||||||
/** 协议判断不能依赖尚未获准初始化的 MMKV 或其他 SDK。 */
|
|
||||||
object PrivacyConsentStore {
|
|
||||||
private lateinit var preferences: SharedPreferences
|
|
||||||
|
|
||||||
fun initialize(context: Context) {
|
|
||||||
preferences = context.getSharedPreferences("privacy_consent", Context.MODE_PRIVATE)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isAccepted(): Boolean = preferences.getBoolean("accepted", false)
|
|
||||||
|
|
||||||
fun setAccepted(accepted: Boolean) {
|
|
||||||
// 在启动小程序等独立进程前落盘,保证它们读取到明确的授权状态。
|
|
||||||
check(preferences.edit().putBoolean("accepted", accepted).commit()) {
|
|
||||||
"无法保存隐私协议状态"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -3,9 +3,15 @@ package com.img.rabbit.provider.utils
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import com.img.rabbit.R
|
import com.img.rabbit.R
|
||||||
|
import okhttp3.internal.platform.ContextAwarePlatform
|
||||||
|
import okhttp3.internal.platform.Platform
|
||||||
|
|
||||||
object HeadParamUtils {
|
object HeadParamUtils {
|
||||||
var applicationContext: Context? = null
|
var applicationContext: Context?
|
||||||
|
get() = (Platform.get() as? ContextAwarePlatform)?.applicationContext
|
||||||
|
set(value) {
|
||||||
|
(Platform.get() as? ContextAwarePlatform)?.applicationContext = value
|
||||||
|
}
|
||||||
|
|
||||||
fun getAppVersionName(): String? {
|
fun getAppVersionName(): String? {
|
||||||
return try {
|
return try {
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,11 @@
|
||||||
package com.img.rabbit.provider.utils
|
package com.img.rabbit.provider.utils
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
import com.github.gzuliyujiang.oaid.DeviceIdentifier
|
import com.github.gzuliyujiang.oaid.DeviceIdentifier
|
||||||
import com.img.rabbit.provider.storage.PreferenceUtil
|
import com.img.rabbit.provider.storage.PreferenceUtil
|
||||||
import com.img.rabbit.BuildConfig
|
import com.img.rabbit.BuildConfig
|
||||||
import com.img.rabbit.config.Constants
|
import com.img.rabbit.config.Constants
|
||||||
|
import com.img.rabbit.config.Constants.LOG_REQUEST
|
||||||
import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext
|
import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext
|
||||||
import com.img.rabbit.provider.utils.HeadParamUtils.getAppVersionName
|
import com.img.rabbit.provider.utils.HeadParamUtils.getAppVersionName
|
||||||
import com.img.rabbit.utils.ChannelUtils
|
import com.img.rabbit.utils.ChannelUtils
|
||||||
|
|
@ -31,6 +33,22 @@ class HeaderInterceptor : Interceptor {
|
||||||
mBuilder.header("x-click-id", "${ChannelUtils.getBdVid(applicationContext)}")
|
mBuilder.header("x-click-id", "${ChannelUtils.getBdVid(applicationContext)}")
|
||||||
mBuilder.header("x-app-id", Constants.AppId)
|
mBuilder.header("x-app-id", Constants.AppId)
|
||||||
|
|
||||||
|
val stringBuilder = StringBuilder()
|
||||||
|
stringBuilder.append("-------------> 📤 header start<-------------\n")
|
||||||
|
stringBuilder.append("│ x-token = $accessToken\n")
|
||||||
|
stringBuilder.append("│ x-version = ${getAppVersionName()}\n")
|
||||||
|
stringBuilder.append("│ x-device-id = ${DeviceIdentifier.getAndroidID(applicationContext)}\n")
|
||||||
|
stringBuilder.append("│ x-mobile-brand = ${android.os.Build.BRAND}\n")
|
||||||
|
stringBuilder.append("│ x-mobile-model = ${android.os.Build.MODEL}\n")
|
||||||
|
stringBuilder.append("│ x-base-version = ${getAppVersionName()}\n")
|
||||||
|
stringBuilder.append("│ x-channel = ${ChannelUtils.getChannel(applicationContext)}\n")
|
||||||
|
stringBuilder.append("│ x-click-id = ${ChannelUtils.getBdVid(applicationContext)}\n")
|
||||||
|
stringBuilder.append("│ x-package = ${BuildConfig.APPLICATION_ID}\n")
|
||||||
|
stringBuilder.append("-------------> header end <-------------")
|
||||||
|
|
||||||
|
Log.i(LOG_REQUEST, stringBuilder.toString())
|
||||||
|
|
||||||
|
|
||||||
val request = mBuilder
|
val request = mBuilder
|
||||||
.method(original.method, original.body)
|
.method(original.method, original.body)
|
||||||
.build()
|
.build()
|
||||||
|
|
|
||||||
|
|
@ -1,26 +1,85 @@
|
||||||
package com.img.rabbit.provider.utils
|
package com.img.rabbit.provider.utils
|
||||||
|
|
||||||
|
import android.text.TextUtils
|
||||||
|
import android.util.Log
|
||||||
import com.img.rabbit.BuildConfig
|
import com.img.rabbit.BuildConfig
|
||||||
import com.img.rabbit.config.Constants
|
import com.img.rabbit.config.Constants
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
import com.img.rabbit.utils.AESpkcs7paddingUtil
|
||||||
import okhttp3.Interceptor
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
import okhttp3.Response
|
import okhttp3.Response
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.nio.charset.Charset
|
||||||
|
import java.nio.charset.UnsupportedCharsetException
|
||||||
|
|
||||||
/** 签名和解密由 Batiao SDK 处理,此处仅保留业务接口的 HTTP 400 兼容。 */
|
|
||||||
|
/**
|
||||||
|
* 解密数据
|
||||||
|
*/
|
||||||
class ResponseInterceptor : Interceptor {
|
class ResponseInterceptor : Interceptor {
|
||||||
private val baseUrl = (if (BuildConfig.DEBUG) Constants.DEBUG_BASE_URL else Constants.RELEASE_BASE_URL).toHttpUrl()
|
private val TAG = "Decode"
|
||||||
|
|
||||||
override fun intercept(chain: Interceptor.Chain): Response {
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
val request = chain.request()
|
val request = chain.request()
|
||||||
val response = chain.proceed(request)
|
val url = request.url
|
||||||
val isBackend = request.url.scheme == baseUrl.scheme &&
|
val apiPath = String.format("%s", url)
|
||||||
request.url.host == baseUrl.host && request.url.port == baseUrl.port
|
val baseUrl = if (BuildConfig.DEBUG) {
|
||||||
return if (isBackend && response.code == 400 &&
|
Constants.DEBUG_BASE_URL
|
||||||
response.header("Content-Type").orEmpty().contains("application/json", ignoreCase = true)
|
|
||||||
) {
|
|
||||||
response.newBuilder().code(200).build()
|
|
||||||
} else {
|
} else {
|
||||||
response
|
Constants.RELEASE_BASE_URL
|
||||||
|
}
|
||||||
|
//如果请求的不是服务端的接口则不用加密
|
||||||
|
if (!apiPath.startsWith(baseUrl)) {
|
||||||
|
return chain.proceed(request)
|
||||||
|
}
|
||||||
|
val response = chain.proceed(request)
|
||||||
|
var charset = Charset.forName("UTF-8")
|
||||||
|
val contentType = response.header("Content-Type")
|
||||||
|
if (contentType != null && contentType.contains("application/json")) {
|
||||||
|
val responseBody = response.body
|
||||||
|
val source = responseBody.source()
|
||||||
|
source.request(Long.MAX_VALUE)
|
||||||
|
val buffer = source.buffer
|
||||||
|
val mediaType = responseBody.contentType()
|
||||||
|
if (mediaType != null) {
|
||||||
|
try {
|
||||||
|
charset = mediaType.charset(Charset.forName("UTF-8"))
|
||||||
|
} catch (e: UnsupportedCharsetException) {
|
||||||
|
e.printStackTrace()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val respBody = buffer.clone().readString(charset!!)
|
||||||
|
Log.w(TAG, "response=${respBody}")
|
||||||
|
if (TextUtils.isEmpty(respBody)) {
|
||||||
|
val responseCode = if (response.code == 400) 200 else response.code //兼容某些接口400的情况
|
||||||
|
return response.newBuilder().code(responseCode).body(responseBody).build()
|
||||||
|
}
|
||||||
|
|
||||||
|
val isEncrypt = JSONObject(respBody).optBoolean("encrypt")
|
||||||
|
Log.w(TAG, "是否需要解密:$isEncrypt")
|
||||||
|
if (!isEncrypt) { //如果不需要加密 直接返回
|
||||||
|
Log.w(TAG, "response=${response.body}")
|
||||||
|
val responseCode = if (response.code == 400) 200 else response.code //兼容某些接口400的情况
|
||||||
|
return response.newBuilder().code(responseCode).body(responseBody).build()
|
||||||
|
}
|
||||||
|
val decrybody = JSONObject(respBody).optString("data")
|
||||||
|
Log.w(TAG, "Json解析后的字符串为---->$decrybody")
|
||||||
|
var decryString: String?
|
||||||
|
try {
|
||||||
|
decryString = AESpkcs7paddingUtil.decryptNormal(decrybody, Constants.AESDecrypt)
|
||||||
|
Log.w("ResponseInterceptor", "解密后返回的字符串为---->$decryString")
|
||||||
|
|
||||||
|
//这里可以通过code处理token过去过期的情况
|
||||||
|
//val decCode = JSONObject(decryString).optInt("code")
|
||||||
|
|
||||||
|
//返回新创建的response
|
||||||
|
val responseCode = if (response.code == 400 && decrybody != null) 200 else response.code //兼容某些接口400的情况
|
||||||
|
return response.newBuilder().code(responseCode).body(decryString.toResponseBody("text/plain".toMediaType())).build()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
package com.img.rabbit.route
|
|
||||||
|
|
||||||
/** 仅允许跳转宿主已注册的原生页面,未知配置不传给 NavController。 */
|
|
||||||
internal object HomeBannerRoutes {
|
|
||||||
private val routes = setOf(
|
|
||||||
ScreenRoute.Home.route, ScreenRoute.Mine.route,
|
|
||||||
ScreenRoute.Cutout.route, ScreenRoute.Resize.route, ScreenRoute.Format.route,
|
|
||||||
ScreenRoute.CameraGuide.route, ScreenRoute.LongImage.route,
|
|
||||||
ScreenRoute.Feedback.route, ScreenRoute.Login.route, ScreenRoute.Setting.route,
|
|
||||||
ScreenRoute.BindAccount.route, ScreenRoute.ManagerAccount.route,
|
|
||||||
ScreenRoute.AboutMine.route, ScreenRoute.DeleteAccount.route,
|
|
||||||
)
|
|
||||||
|
|
||||||
fun resolve(route: String?): String? = route?.takeIf { it in routes }
|
|
||||||
}
|
|
||||||
|
|
@ -11,30 +11,21 @@ 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 {
|
||||||
private FrameLayout splashView;
|
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 (splashWindow != null) {
|
if(rootView != null)
|
||||||
splashWindow.close();
|
|
||||||
splashWindow = null;
|
|
||||||
}
|
|
||||||
if (rootView != null && splashView != null) {
|
|
||||||
rootView.removeView(splashView);
|
rootView.removeView(splashView);
|
||||||
}
|
}
|
||||||
splashView = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,95 +0,0 @@
|
||||||
package com.img.rabbit.uni
|
|
||||||
|
|
||||||
import android.app.Activity
|
|
||||||
import android.app.Application
|
|
||||||
import android.graphics.Color
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.view.View
|
|
||||||
import android.view.ViewTreeObserver
|
|
||||||
import android.view.Window
|
|
||||||
import android.view.WindowManager
|
|
||||||
import io.dcloud.feature.sdk.DCUniMPActivity
|
|
||||||
|
|
||||||
/** 在各 UniMP 进程中维持底部沉浸,覆盖启动图关闭、页面切换和后台返回。 */
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
object UniMPImmersiveWindow {
|
|
||||||
fun register(application: Application) {
|
|
||||||
application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
|
|
||||||
private val controllers = mutableMapOf<Activity, Controller>()
|
|
||||||
|
|
||||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
|
|
||||||
// 包含 DCUniMPActivity0..4 和 DCUniMPTopActivity0..4;不改宿主及支付等页面。
|
|
||||||
if (activity is DCUniMPActivity) {
|
|
||||||
controllers[activity] = Controller(activity.window)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onActivityResumed(activity: Activity) {
|
|
||||||
controllers[activity]?.apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onActivityDestroyed(activity: Activity) {
|
|
||||||
controllers.remove(activity)?.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onActivityStarted(activity: Activity) = Unit
|
|
||||||
override fun onActivityPaused(activity: Activity) = Unit
|
|
||||||
override fun onActivityStopped(activity: Activity) = Unit
|
|
||||||
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun apply(window: Window) {
|
|
||||||
val flags = window.attributes.flags
|
|
||||||
if (flags and WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS == 0) {
|
|
||||||
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
|
|
||||||
}
|
|
||||||
if (flags and WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION != 0) {
|
|
||||||
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
|
|
||||||
}
|
|
||||||
if (window.navigationBarColor != Color.TRANSPARENT) window.navigationBarColor = Color.TRANSPARENT
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && window.navigationBarDividerColor != Color.TRANSPARENT) {
|
|
||||||
window.navigationBarDividerColor = Color.TRANSPARENT
|
|
||||||
}
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && window.isNavigationBarContrastEnforced) {
|
|
||||||
window.isNavigationBarContrastEnforced = false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 只让内容延伸至导航栏下方。保留 SDK 的状态栏、图标颜色和 adjustResize 输入法处理;
|
|
||||||
// 不隐藏系统手势条,也不消费键盘或状态栏的 WindowInsets。
|
|
||||||
val decor = window.decorView
|
|
||||||
val visibility = decor.systemUiVisibility or
|
|
||||||
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
|
|
||||||
if (decor.systemUiVisibility != visibility) decor.systemUiVisibility = visibility
|
|
||||||
}
|
|
||||||
|
|
||||||
private class Controller(private val window: Window) :
|
|
||||||
ViewTreeObserver.OnGlobalLayoutListener, ViewTreeObserver.OnWindowFocusChangeListener {
|
|
||||||
private val decor = window.decorView
|
|
||||||
private val observer = decor.viewTreeObserver
|
|
||||||
|
|
||||||
init {
|
|
||||||
observer.addOnGlobalLayoutListener(this)
|
|
||||||
observer.addOnWindowFocusChangeListener(this)
|
|
||||||
apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun apply() = UniMPImmersiveWindow.apply(window)
|
|
||||||
|
|
||||||
override fun onGlobalLayout() = apply()
|
|
||||||
|
|
||||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
|
||||||
if (hasFocus) apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun close() {
|
|
||||||
// 未附着时注册的 ViewTreeObserver 会合并到附着后的 observer。
|
|
||||||
val activeObserver = if (observer.isAlive) observer else decor.viewTreeObserver
|
|
||||||
if (activeObserver.isAlive) {
|
|
||||||
activeObserver.removeOnGlobalLayoutListener(this)
|
|
||||||
activeObserver.removeOnWindowFocusChangeListener(this)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,125 +0,0 @@
|
||||||
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
|
|
||||||
import io.dcloud.feature.sdk.DCUniMPActivity
|
|
||||||
|
|
||||||
/** 启动图期间设置导航图标明暗,关闭后交由 UniMP 正文的沉浸控制器接管。 */
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
class UniMPSplashWindow(
|
|
||||||
context: Context,
|
|
||||||
private val splashView: View,
|
|
||||||
private val darkNavigationIcons: Boolean,
|
|
||||||
) :
|
|
||||||
View.OnAttachStateChangeListener, ViewTreeObserver.OnGlobalLayoutListener {
|
|
||||||
|
|
||||||
private val activity = findActivity(context)
|
|
||||||
private val window = activity?.window
|
|
||||||
private val originalNavigationBarColor = window?.navigationBarColor
|
|
||||||
private val originalSystemUiVisibility = window?.decorView?.systemUiVisibility ?: 0
|
|
||||||
private val originalWindowFlags = window?.attributes?.flags ?: 0
|
|
||||||
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
|
|
||||||
// 启动图关闭时立即接续底部沉浸,避免恢复窗口后先露出一帧安全区底色。
|
|
||||||
if (activity is DCUniMPActivity) UniMPImmersiveWindow.apply(window)
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -12,30 +12,21 @@ 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 {
|
||||||
private FrameLayout splashView;
|
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 (splashWindow != null) {
|
if(rootView != null)
|
||||||
splashWindow.close();
|
|
||||||
splashWindow = null;
|
|
||||||
}
|
|
||||||
if (rootView != null && splashView != null) {
|
|
||||||
rootView.removeView(splashView);
|
rootView.removeView(splashView);
|
||||||
}
|
}
|
||||||
splashView = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ object AppEventBus {
|
||||||
)
|
)
|
||||||
val events = _events.asSharedFlow()
|
val events = _events.asSharedFlow()
|
||||||
*/
|
*/
|
||||||
private val _events = MutableSharedFlow<Any>(extraBufferCapacity = 16)
|
private val _events = MutableSharedFlow<Any>()
|
||||||
val events = _events.asSharedFlow()
|
val events = _events.asSharedFlow()
|
||||||
|
|
||||||
suspend fun post(event: UniMpWXPayEvent) {
|
suspend fun post(event: UniMpWXPayEvent) {
|
||||||
|
|
@ -27,9 +27,6 @@ object AppEventBus {
|
||||||
suspend fun post(event: WXAuthEvent) {
|
suspend fun post(event: WXAuthEvent) {
|
||||||
_events.emit(event)
|
_events.emit(event)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Callback Activities must close even when a subscriber is temporarily busy.
|
|
||||||
fun tryPost(event: WXAuthEvent): Boolean = _events.tryEmit(event)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -56,7 +53,6 @@ sealed class LoginBindEvent {
|
||||||
*/
|
*/
|
||||||
sealed class WXAuthEvent {
|
sealed class WXAuthEvent {
|
||||||
data class AuthResult(val code: String, val authType: Int) : WXAuthEvent()
|
data class AuthResult(val code: String, val authType: Int) : WXAuthEvent()
|
||||||
data class AuthFailure(val message: String) : WXAuthEvent()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -72,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, val pagePath: String? = null) : GlobalEvent()
|
data class ShowUniDownloadNotify(val entity: UniVersionEntity) : GlobalEvent()
|
||||||
data class ShowUniUpdateNotify(val entity: UniVersionEntity, val pagePath: String? = null) : GlobalEvent()
|
data class ShowUniUpdateNotify(val entity: UniVersionEntity) : GlobalEvent()
|
||||||
}
|
}
|
||||||
|
|
||||||
object GlobalEventBus {
|
object GlobalEventBus {
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ import android.content.Context
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.text.TextUtils
|
import android.text.TextUtils
|
||||||
import com.alibaba.fastjson.JSON
|
import com.alibaba.fastjson.JSON
|
||||||
import com.batiao.batiaosdk.PackageSpliter
|
|
||||||
import com.bytedance.hume.readapk.HumeSDK
|
import com.bytedance.hume.readapk.HumeSDK
|
||||||
import com.img.rabbit.BuildConfig
|
import com.img.rabbit.BuildConfig
|
||||||
import com.img.rabbit.utils.appwalle.ChannelReader
|
import com.img.rabbit.utils.appwalle.ChannelReader
|
||||||
|
|
@ -38,8 +37,7 @@ object ChannelUtils {
|
||||||
if (!TextUtils.isEmpty(juliang)) {
|
if (!TextUtils.isEmpty(juliang)) {
|
||||||
return juliang
|
return juliang
|
||||||
}
|
}
|
||||||
// 保留 Rabbit 的渠道命名和 manifest 兜底,优先读取 Batiao 分包渠道。
|
return channel(context)
|
||||||
return PackageSpliter.getBatiaoChannel(channel(context))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun channel(context: Context): String {
|
private fun channel(context: Context): String {
|
||||||
|
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
package com.img.rabbit.utils
|
|
||||||
|
|
||||||
/** Choose the sampling factor before allocating pixels, including for very large camera images. */
|
|
||||||
internal fun imageSampleSize(width: Int, height: Int, maxDimension: Int): Int {
|
|
||||||
require(maxDimension > 0)
|
|
||||||
var sampleSize = 1
|
|
||||||
val longestSide = maxOf(width, height).toLong()
|
|
||||||
while ((longestSide + sampleSize - 1) / sampleSize > maxDimension) {
|
|
||||||
sampleSize *= 2
|
|
||||||
}
|
|
||||||
return sampleSize
|
|
||||||
}
|
|
||||||
|
|
@ -205,19 +205,10 @@ object ImageUtils {
|
||||||
* @param uri 图片URI
|
* @param uri 图片URI
|
||||||
* @return Bitmap对象,如果获取失败则返回null
|
* @return Bitmap对象,如果获取失败则返回null
|
||||||
*/
|
*/
|
||||||
fun getBitmapFromUri(context: Context, uri: Uri, maxDimension: Int? = null): Bitmap? {
|
fun getBitmapFromUri(context: Context, uri: Uri): Bitmap? {
|
||||||
return try {
|
return try {
|
||||||
val options = BitmapFactory.Options()
|
|
||||||
if (maxDimension != null) {
|
|
||||||
options.inJustDecodeBounds = true
|
|
||||||
context.contentResolver.openInputStream(uri)?.use {
|
|
||||||
BitmapFactory.decodeStream(it, null, options)
|
|
||||||
}
|
|
||||||
options.inSampleSize = imageSampleSize(options.outWidth, options.outHeight, maxDimension)
|
|
||||||
options.inJustDecodeBounds = false
|
|
||||||
}
|
|
||||||
context.contentResolver.openInputStream(uri)?.use { inputStream ->
|
context.contentResolver.openInputStream(uri)?.use { inputStream ->
|
||||||
BitmapFactory.decodeStream(inputStream, null, options)
|
BitmapFactory.decodeStream(inputStream)
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e("ImageUtils", "从URI获取Bitmap失败", e)
|
Log.e("ImageUtils", "从URI获取Bitmap失败", e)
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,12 @@
|
||||||
package com.img.rabbit.utils
|
package com.img.rabbit.utils
|
||||||
|
|
||||||
import android.graphics.*
|
import android.graphics.*
|
||||||
import android.util.Log
|
|
||||||
import com.google.mlkit.vision.common.InputImage
|
import com.google.mlkit.vision.common.InputImage
|
||||||
import com.google.mlkit.vision.segmentation.Segmentation
|
import com.google.mlkit.vision.segmentation.Segmentation
|
||||||
import com.google.mlkit.vision.segmentation.selfie.SelfieSegmenterOptions
|
import com.google.mlkit.vision.segmentation.selfie.SelfieSegmenterOptions
|
||||||
import androidx.core.graphics.createBitmap
|
import androidx.core.graphics.createBitmap
|
||||||
|
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
import java.util.concurrent.Executors
|
|
||||||
|
|
||||||
// 变换状态模型
|
// 变换状态模型
|
||||||
data class TransformState(
|
data class TransformState(
|
||||||
|
|
@ -20,7 +18,6 @@ data class TransformState(
|
||||||
|
|
||||||
|
|
||||||
object PhotoCutter {
|
object PhotoCutter {
|
||||||
private val executor = Executors.newSingleThreadExecutor()
|
|
||||||
|
|
||||||
fun cutPureHead(sourceBitmap: Bitmap, callback: (Bitmap?) -> Unit) {
|
fun cutPureHead(sourceBitmap: Bitmap, callback: (Bitmap?) -> Unit) {
|
||||||
// 1. 配置分割器:单图模式
|
// 1. 配置分割器:单图模式
|
||||||
|
|
@ -28,42 +25,29 @@ object PhotoCutter {
|
||||||
.setDetectorMode(SelfieSegmenterOptions.SINGLE_IMAGE_MODE)
|
.setDetectorMode(SelfieSegmenterOptions.SINGLE_IMAGE_MODE)
|
||||||
.build()
|
.build()
|
||||||
val segmenter = Segmentation.getClient(options)
|
val segmenter = Segmentation.getClient(options)
|
||||||
try {
|
|
||||||
val image = InputImage.fromBitmap(sourceBitmap, 0)
|
val image = InputImage.fromBitmap(sourceBitmap, 0)
|
||||||
// Mask conversion belongs off the UI thread; exceptions here are asynchronous.
|
|
||||||
segmenter.process(image).addOnCompleteListener(executor) { task ->
|
// 2. 开始处理
|
||||||
val result = try {
|
segmenter.process(image)
|
||||||
val mask = task.result
|
.addOnSuccessListener { mask ->
|
||||||
generateTransparentBitmap(sourceBitmap, mask.buffer, mask.width, mask.height)
|
val resultBitmap = generateTransparentBitmap(sourceBitmap, mask.buffer)
|
||||||
} catch (e: Exception) {
|
callback(resultBitmap)
|
||||||
Log.e("PhotoCutter", "本地抠图失败", e)
|
|
||||||
null
|
|
||||||
} finally {
|
|
||||||
segmenter.close()
|
|
||||||
}
|
}
|
||||||
callback(result)
|
.addOnFailureListener {
|
||||||
}
|
callback(null)
|
||||||
} catch (e: Exception) {
|
|
||||||
segmenter.close()
|
|
||||||
throw e
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun generateTransparentBitmap(
|
private fun generateTransparentBitmap(
|
||||||
source: Bitmap,
|
source: Bitmap,
|
||||||
maskBuffer: java.nio.ByteBuffer,
|
maskBuffer: java.nio.ByteBuffer,
|
||||||
maskWidth: Int,
|
|
||||||
maskHeight: Int,
|
|
||||||
): Bitmap {
|
): Bitmap {
|
||||||
val width = source.width
|
val width = source.width
|
||||||
val height = source.height
|
val height = source.height
|
||||||
|
val result = createBitmap(width, height)
|
||||||
|
|
||||||
// 将掩码缓冲区重置
|
// 将掩码缓冲区重置
|
||||||
maskBuffer.rewind()
|
maskBuffer.rewind()
|
||||||
require(maskWidth > 0 && maskHeight > 0 &&
|
|
||||||
maskBuffer.remaining().toLong() >= maskWidth.toLong() * maskHeight * 4) {
|
|
||||||
"无效的人像掩码"
|
|
||||||
}
|
|
||||||
|
|
||||||
// 逐像素处理
|
// 逐像素处理
|
||||||
val pixels = IntArray(width * height)
|
val pixels = IntArray(width * height)
|
||||||
|
|
@ -71,9 +55,7 @@ object PhotoCutter {
|
||||||
|
|
||||||
for (i in 0 until width * height) {
|
for (i in 0 until width * height) {
|
||||||
// 获取当前像素的人像概率(0.0 ~ 1.0)
|
// 获取当前像素的人像概率(0.0 ~ 1.0)
|
||||||
val maskX = (i % width).toLong() * maskWidth / width
|
val confidence = maskBuffer.float
|
||||||
val maskY = (i / width).toLong() * maskHeight / height
|
|
||||||
val confidence = maskBuffer.getFloat(((maskY * maskWidth + maskX) * 4).toInt())
|
|
||||||
|
|
||||||
// 如果置信度低于 0.5,认为该像素是背景,设为完全透明
|
// 如果置信度低于 0.5,认为该像素是背景,设为完全透明
|
||||||
if (confidence < 0.5) {
|
if (confidence < 0.5) {
|
||||||
|
|
@ -81,7 +63,6 @@ object PhotoCutter {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val result = createBitmap(width, height)
|
|
||||||
result.setPixels(pixels, 0, width, 0, 0, width, height)
|
result.setPixels(pixels, 0, width, 0, 0, width, height)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,8 @@
|
||||||
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 com.batiao.batiaosdk.unimp.BatiaoUnimp
|
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
|
||||||
|
|
@ -25,328 +23,403 @@ 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 kotlinx.serialization.json.Json
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.Locale
|
import kotlin.jvm.java
|
||||||
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())
|
/**
|
||||||
private val releaseExecutor = Executors.newSingleThreadExecutor()
|
* 所有运行的UniMp小程序实体
|
||||||
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?) {
|
||||||
_uniMpFlow.update { it + (id to mp) }
|
val currentMap = _uniMpFlow.value.toMutableMap()
|
||||||
|
currentMap[id] = mp
|
||||||
|
_uniMpFlow.value = currentMap
|
||||||
|
}
|
||||||
|
|
||||||
|
//当前正在更新的小程序
|
||||||
|
var currentUpdateUniMp: UniVersionEntity? = null
|
||||||
|
//仅当跳转指定小程序时,才需要跳转指定位置
|
||||||
|
var currentUniMpJumpPatch: String? = null
|
||||||
|
|
||||||
|
private fun getWgtName(uniMpId: String): String{
|
||||||
|
return String.format("%s.wgt", uniMpId)
|
||||||
|
//return String.format("%s.zip", uniMpId)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getWgtFile(uniMpId: String): File{
|
private fun getWgtFile(uniMpId: String): File{
|
||||||
require(uniMpId.matches(Regex("[A-Za-z0-9_-]+"))) { "无效的小程序 ID" }
|
val wgtName = getWgtName(uniMpId)
|
||||||
val directory = FileUtils.instance?.cacheUniAppDir ?: File(checkNotNull(applicationContext).cacheDir, "uniApp")
|
return File(FileUtils.instance?.cacheUniAppDir?.absolutePath, wgtName)
|
||||||
return File(directory, "$uniMpId.wgt")
|
}
|
||||||
|
/**
|
||||||
|
*获取当前前台运行的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 getCurrentUniMp(): IUniMP? = uniMpFlow.value.values.firstOrNull { it?.isRunning == true }
|
/**
|
||||||
|
* 是否强制更新
|
||||||
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 =
|
|
||||||
UniMpPolicy.requiresDownload(uniVersion.force, wgtIsExists(uniVersion.unimp_id))
|
|
||||||
|
|
||||||
fun wgtIsExists(uniMpId: String): Boolean = runCatching {
|
|
||||||
getWgtFile(uniMpId).let { it.isFile && it.length() > 0 }
|
|
||||||
}.getOrDefault(false)
|
|
||||||
|
|
||||||
fun isRelease(uniMpId: String): Boolean = DCUniMPSDK.getInstance().isExistsApp(uniMpId)
|
|
||||||
|
|
||||||
fun isBusy(uniMpId: String): Boolean = uniMpId in downloading || uniMpId in releasing
|
|
||||||
|
|
||||||
/** 已运行的小程序直接显示,通过 jump 事件跳转,避免再次 openUniMP。 */
|
|
||||||
fun showRunningUniMp(uniMpId: String, pagePath: String?): Boolean {
|
|
||||||
if (isBusy(uniMpId)) return false
|
|
||||||
return try {
|
|
||||||
val mp = _uniMpFlow.value[uniMpId] ?: return false
|
|
||||||
refreshUniMpHeaders()
|
|
||||||
if ((mp.isRuning || mp.isRunning) && mp.showUniMP()) {
|
|
||||||
mp.sendUniMPEvent("jump", pagePath)
|
|
||||||
true
|
|
||||||
} else false
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "恢复小程序失败,将重新启动: $uniMpId", e)
|
|
||||||
updateUniMp(uniMpId, null)
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun reportOpen(version: UniVersionEntity, itemName: String, reportViewModel: ReportViewModel) {
|
/**
|
||||||
report(reportViewModel, ReportType.CLICK,
|
* 是否需要下载(强制更新或者不存在wgt文件)
|
||||||
if (version.unimp_type == "wx") ReportKey.EVENT_CLIENT_OPEN_WX_UNIMP else ReportKey.EVENT_CLIENT_OPEN_ALIPAY_UNIMP,
|
*/
|
||||||
itemName, "")
|
fun isDownloadUniMp(uniVersion: UniVersionEntity): Boolean{
|
||||||
|
val wgtFile = getWgtFile(uniVersion.unimp_id)
|
||||||
|
return isUpdateForce(uniVersion) || !(FileUtils.instance?.fileIsExists(wgtFile) == true && FileUtils.getFileSize(wgtFile) > 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun reportUpdateChoice(version: UniVersionEntity, confirmed: Boolean, reportViewModel: ReportViewModel) {
|
fun wgtIsExists(uniMpId: String): Boolean{
|
||||||
report(reportViewModel, ReportType.CLICK,
|
|
||||||
if (confirmed) ReportKey.EVENT_CLIENT_CONFIRM_DOWNLOAD_UNIMP else ReportKey.EVENT_CLIENT_CANCEL_DOWNLOAD_UNIMP,
|
|
||||||
"", Json.encodeToString(version))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun distributeUniMp(
|
|
||||||
context: Context,
|
|
||||||
uniVersion: UniVersionEntity,
|
|
||||||
reportViewModel: ReportViewModel,
|
|
||||||
pagePath: String? = null,
|
|
||||||
onResult: (loading: Boolean) -> Unit,
|
|
||||||
) = onMain {
|
|
||||||
if (isBusy(uniVersion.unimp_id)) {
|
|
||||||
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
|
|
||||||
}
|
|
||||||
releaseExecutor.execute {
|
|
||||||
try {
|
|
||||||
val wgtFile = getWgtFile(uniMpId)
|
val wgtFile = getWgtFile(uniMpId)
|
||||||
check(wgtFile.isFile && wgtFile.length() > 0) { "资源包不存在或为空" }
|
//判断wgt是否下载
|
||||||
val config = PreferenceUtil.getUserConfig()?.config
|
return FileUtils.instance?.fileIsExists(wgtFile) == true && FileUtils.getFileSize(wgtFile) > 0
|
||||||
val releaseConfig = UniMPReleaseConfiguration().apply {
|
|
||||||
wgtPath = wgtFile.absolutePath
|
|
||||||
password = UniMpPolicy.releasePassword(config?.wgtPassword, config?.uniPassword)
|
|
||||||
}
|
}
|
||||||
DCUniMPSDK.getInstance().releaseWgtToRunPath(uniMpId, releaseConfig) { code, args ->
|
|
||||||
if (code == 1) {
|
fun isRelease(uniMpId: String): Boolean{
|
||||||
onMain {
|
return DCUniMPSDK.getInstance().isExistsApp(uniMpId)
|
||||||
releasing.remove(uniMpId)
|
|
||||||
onRelease(true)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查更新
|
||||||
|
*/
|
||||||
|
private fun checkUpdate(uniVersion: UniVersionEntity, currentVersion: String): Boolean {
|
||||||
|
val version = uniVersion.version
|
||||||
|
if(version.isEmpty())return false
|
||||||
|
|
||||||
|
val newVersions = version.split(".")
|
||||||
|
val originVersions = currentVersion.split(".")
|
||||||
|
|
||||||
|
if(newVersions.size != 3 || originVersions.size != 3)return false
|
||||||
|
|
||||||
|
for (i in 0..2) {
|
||||||
|
val newVal = newVersions[i].toIntOrNull() ?: 0
|
||||||
|
val oldVal = originVersions[i].toIntOrNull() ?: 0
|
||||||
|
|
||||||
|
if (newVal > oldVal) {
|
||||||
|
return true
|
||||||
|
} else if (newVal < oldVal) {
|
||||||
|
return 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{
|
}else{
|
||||||
releaseFailure(uniMpId, "SDK 释放失败提示。错误码: $code, 原因提示: $args", reportViewModel, onRelease)
|
//资源未释放,先释放后启动
|
||||||
|
releaseWgt(uniVersion,reportViewModel){ isSuccess, versionEntity ->
|
||||||
|
if(isSuccess){
|
||||||
|
startUniMp(context, versionEntity, onResult)
|
||||||
|
}else{
|
||||||
|
onResult(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
|
||||||
releaseFailure(uniMpId, "释放小程序资源包异常: ${e.message.orEmpty()}", reportViewModel, onRelease)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun releaseFailure(uniMpId: String, reason: String, reportViewModel: ReportViewModel, onRelease: (Boolean) -> Unit) {
|
private fun startUniMp(context: Context, uniVersion: UniVersionEntity, onResult:(loading: Boolean) -> Unit){
|
||||||
releaseExecutor.execute {
|
val uniMp = _uniMpFlow.value[uniVersion.unimp_id]//uniMpPair[uniVersion.unimp_id]
|
||||||
runCatching {
|
if(uniMp?.isRuning == true){
|
||||||
getWgtFile(uniMpId).delete()
|
uniMp.showUniMP()
|
||||||
val basePath = DCUniMPSDK.getInstance().getAppBasePath(applicationContext)
|
}else{
|
||||||
File(basePath, uniMpId).deleteRecursively()
|
val configuration = getUniMPOpenConfiguration()
|
||||||
}.onFailure { Log.w(TAG, "清理失败的小程序资源异常", it) }
|
if(uniVersion.unimp_type == "wx"){
|
||||||
onMain {
|
configuration.splashClass = UniMPWxSplashView::class.java
|
||||||
releasing.remove(uniMpId)
|
}else if("alipay" == uniVersion.unimp_type){
|
||||||
updateUniMp(uniMpId, null)
|
configuration.splashClass = UniMPAlipaySplashView::class.java
|
||||||
Log.e(TAG, reason)
|
}
|
||||||
report(reportViewModel, ReportType.ERROR, ReportKey.EVENT_CLIENT_UNI_RELEASE_WGT, uniMpId, reason)
|
updateUniMp(uniVersion.unimp_id, DCUniMPSDK.getInstance().openUniMP(context, uniVersion.unimp_id, configuration))
|
||||||
|
}
|
||||||
|
onResult(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动小程序并直达指定页面
|
||||||
|
*/
|
||||||
|
fun startUniMpPage(context: Context, uniMpId: String, uniMpType: String, pagePath: String, reportViewModel: ReportViewModel){
|
||||||
|
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) {
|
||||||
|
releaseWgt(versionEntity.unimp_id,reportViewModel){ isSuccess ->
|
||||||
|
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("加载失败,请重试或联系客服!")
|
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)
|
onRelease(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}else if(uniState == UniMpUpdate.DOWNLOAD_FAIL){
|
||||||
|
onProgress(UniMpUpdate.DOWNLOAD_FAIL, -1f)
|
||||||
/** 新包下载完成后始终重新释放,避免仍启动旧的运行目录。 */
|
|
||||||
fun downloadWGT(
|
|
||||||
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(
|
private fun downloadUniMp(
|
||||||
scope: CoroutineScope,
|
scope: CoroutineScope,
|
||||||
version: UniVersionEntity,
|
uniVersion: UniVersionEntity,
|
||||||
reportViewModel: ReportViewModel,
|
onProgress:(state:UniMpUpdate,filePath: String?, progress: Float) -> Unit
|
||||||
onProgress: (UniMpUpdate, String?, Float?) -> Unit,
|
) {
|
||||||
onDownloaded: () -> Unit,
|
val extension = MimeTypeMap.getFileExtensionFromUrl(uniVersion.url)
|
||||||
) = onMain {
|
if(extension != "zip" && extension != "wgt"){
|
||||||
val id = version.unimp_id
|
CenterToast.show("资源文件格式不被支持...")
|
||||||
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)
|
onProgress(UniMpUpdate.DOWNLOAD_FAIL, null, -1f)
|
||||||
return@launch
|
return
|
||||||
} finally {
|
}
|
||||||
downloading.remove(id)
|
|
||||||
|
val uniMpId = uniVersion.unimp_id
|
||||||
|
val wgtName = getWgtName(uniMpId)
|
||||||
|
val path = FileUtils.instance?.cacheUniAppDir?.absolutePath?:""
|
||||||
|
//先删除旧文件
|
||||||
|
val oldFile = File(path, wgtName)
|
||||||
|
if(oldFile.exists()){
|
||||||
|
|
||||||
|
oldFile.delete()
|
||||||
|
}
|
||||||
|
onProgress(UniMpUpdate.DOWNLOAD_LOADING, null, 0.0f)
|
||||||
|
|
||||||
|
scope.launch {
|
||||||
|
val isAvailable = isFileDownloadable(uniVersion.url)
|
||||||
|
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("下载失败...")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
onProgress(UniMpUpdate.DOWNLOAD_FINISH, getWgtFile(id).path, 1f)
|
|
||||||
onDownloaded()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getUniMPOpenConfiguration(uniType: String, pagePath: String?): UniMPOpenConfiguration =
|
private fun getUniMPOpenConfiguration(): UniMPOpenConfiguration{
|
||||||
UniMPOpenConfiguration().apply {
|
val stringBuilder = StringBuilder()
|
||||||
path = pagePath
|
stringBuilder.append("-------------> 📤 header start<-------------\n")
|
||||||
splashClass = if (uniType == "alipay") UniMPAlipaySplashView::class.java else UniMPWxSplashView::class.java
|
stringBuilder.append("│ x-token = ${PreferenceUtil.getXToken()}\n")
|
||||||
// 同时保留 extraData,兼容尚未使用 Batiao 网络桥接的旧版小程序。
|
stringBuilder.append("│ x-version = ${getAppVersionName()}\n")
|
||||||
refreshUniMpHeaders().forEach { (key, value) -> extraData.put(key, value) }
|
stringBuilder.append("│ x-platform = android\n")
|
||||||
extraData.put("host", "${Constants.RELEASE_BASE_URL.trimEnd('/')}/")
|
stringBuilder.append("│ x-device-id = ${DeviceIdentifier.getAndroidID(applicationContext)}\n")
|
||||||
|
stringBuilder.append("│ x-mobile-brand = ${android.os.Build.BRAND}\n")
|
||||||
|
stringBuilder.append("│ x-mobile-model = ${android.os.Build.MODEL}\n")
|
||||||
|
stringBuilder.append("│ x-channel = ${ChannelUtils.getChannel(applicationContext)}\n")
|
||||||
|
stringBuilder.append("│ x-package = ${BuildConfig.APPLICATION_ID}\n")
|
||||||
|
stringBuilder.append("│ x-click-id = ${ChannelUtils.getBdVid(applicationContext)}\n")
|
||||||
|
stringBuilder.append("│ host = ${Constants.RELEASE_BASE_URL}\n")
|
||||||
|
stringBuilder.append("│ decrypt = ${Constants.AESDecrypt}\n")
|
||||||
|
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()?:"")
|
||||||
|
extraData.put("x-version", getAppVersionName()?:"")
|
||||||
|
extraData.put("x-platform", "android")
|
||||||
|
extraData.put("x-device-id", DeviceIdentifier.getAndroidID(applicationContext))
|
||||||
|
extraData.put("x-mobile-brand", android.os.Build.BRAND)
|
||||||
|
extraData.put("x-mobile-model", android.os.Build.MODEL)
|
||||||
|
extraData.put("x-channel", ChannelUtils.getChannel(applicationContext))
|
||||||
|
extraData.put("x-package", BuildConfig.APPLICATION_ID)
|
||||||
|
extraData.put("x-click-id",ChannelUtils.getBdVid(applicationContext))
|
||||||
|
extraData.put("host", "${Constants.RELEASE_BASE_URL}/")
|
||||||
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")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshUniMpHeaders(): Map<String, String> {
|
|
||||||
val headers = linkedMapOf(
|
|
||||||
"x-token" to PreferenceUtil.getXToken().orEmpty(),
|
|
||||||
"x-version" to getAppVersionName().orEmpty(),
|
|
||||||
"x-platform" to "android",
|
|
||||||
"x-device-id" to DeviceIdentifier.getAndroidID(applicationContext).orEmpty(),
|
|
||||||
"x-mobile-brand" to android.os.Build.BRAND,
|
|
||||||
"x-mobile-model" to android.os.Build.MODEL,
|
|
||||||
"x-channel" to ChannelUtils.getChannel(applicationContext),
|
|
||||||
"x-package" to BuildConfig.APPLICATION_ID,
|
|
||||||
"x-click-id" to ChannelUtils.getBdVid(applicationContext).orEmpty(),
|
|
||||||
"x-base-version" to getAppVersionName().orEmpty(),
|
|
||||||
"x-app-id" to Constants.AppId,
|
|
||||||
)
|
|
||||||
BatiaoUnimp.setHeaders(headers)
|
|
||||||
return headers
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 拉起微信小程序来支付
|
||||||
|
*/
|
||||||
fun startUniPay(api: IWXAPI, weixinMpOriId: String, outTradeNo: String) {
|
fun startUniPay(api: IWXAPI, weixinMpOriId: String, outTradeNo: String) {
|
||||||
val request = WXLaunchMiniProgram.Req().apply {
|
//isStartComboPay = true
|
||||||
userName = weixinMpOriId
|
val req = WXLaunchMiniProgram.Req()
|
||||||
path = "pages/index/index?outTradeNo=$outTradeNo"
|
req.userName = weixinMpOriId // 填小程序原始id
|
||||||
miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE
|
req.path = "pages/index/index?outTradeNo=$outTradeNo" //拉起小程序页面的可带参路径,不填默认拉起小程序首页,对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar"。
|
||||||
}
|
req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE// 可选打开 开发版,体验版和正式版
|
||||||
api.sendReq(request)
|
api.sendReq(req)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun report(viewModel: ReportViewModel, type: String, key: String, value: String, extra: String) {
|
private val okHttpClient: OkHttpClient by lazy {
|
||||||
viewModel.requestReport(ReportRequest(type = type, key = key, value = value, extra = extra))
|
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) {
|
||||||
|
return@withContext response.isSuccessful
|
||||||
|
} else {
|
||||||
|
return@withContext true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
return@withContext false
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
@ -1,206 +0,0 @@
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
package com.img.rabbit.utils
|
|
||||||
|
|
||||||
import com.tencent.mm.opensdk.modelbase.BaseResp
|
|
||||||
|
|
||||||
internal fun wechatAuthResult(errorCode: Int, code: String?): WXAuthEvent = when {
|
|
||||||
errorCode == BaseResp.ErrCode.ERR_OK && !code.isNullOrBlank() ->
|
|
||||||
WXAuthEvent.AuthResult(code, authType = 0)
|
|
||||||
errorCode == BaseResp.ErrCode.ERR_USER_CANCEL ->
|
|
||||||
WXAuthEvent.AuthFailure("已取消微信授权")
|
|
||||||
errorCode == BaseResp.ErrCode.ERR_AUTH_DENIED ->
|
|
||||||
WXAuthEvent.AuthFailure("微信授权被拒绝,请重试")
|
|
||||||
else -> WXAuthEvent.AuthFailure("微信授权失败,请重试")
|
|
||||||
}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
package com.img.rabbit.utils
|
|
||||||
|
|
||||||
import com.tencent.mm.opensdk.constants.Build
|
|
||||||
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat
|
|
||||||
import com.tencent.mm.opensdk.modelmsg.SendAuth
|
|
||||||
import com.tencent.mm.opensdk.openapi.IWXAPI
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
|
|
||||||
/** SDK calls may synchronously query WeChat's ContentProvider. Keep them off the UI thread. */
|
|
||||||
object WechatRequests {
|
|
||||||
suspend fun authorize(api: IWXAPI, state: String): String? = execute {
|
|
||||||
if (!api.isWXAppInstalled) return@execute "您没有安装微信客户端,请先下载安装"
|
|
||||||
val request = SendAuth.Req().apply {
|
|
||||||
scope = "snsapi_userinfo"
|
|
||||||
this.state = state
|
|
||||||
}
|
|
||||||
if (api.sendReq(request)) null else "无法打开微信授权,请重试"
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun customerService(api: IWXAPI, corpId: String?, url: String?): String? = execute {
|
|
||||||
if (!api.isWXAppInstalled) return@execute "未安装微信客户端"
|
|
||||||
if (api.wxAppSupportAPI < Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
|
|
||||||
return@execute "当前微信版本不支持在线客服,请升级微信"
|
|
||||||
}
|
|
||||||
if (corpId.isNullOrBlank() || url.isNullOrBlank()) {
|
|
||||||
return@execute "客服信息暂不可用,请稍后重试"
|
|
||||||
}
|
|
||||||
val request = WXOpenCustomerServiceChat.Req().apply {
|
|
||||||
this.corpId = corpId
|
|
||||||
this.url = url
|
|
||||||
}
|
|
||||||
if (api.sendReq(request)) null else "无法打开微信客服,请重试"
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun execute(block: () -> String?): String? = withContext(Dispatchers.IO) {
|
|
||||||
try {
|
|
||||||
block()
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
|
||||||
"微信暂时无法响应,请稍后重试"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -39,6 +39,7 @@ class AccountBindViewModel : BaseViewModel() {
|
||||||
if(wechatCode.isEmpty()){
|
if(wechatCode.isEmpty()){
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
PreferenceUtil.saveWxCode(wechatCode)
|
||||||
|
|
||||||
// 调用 API 获取数据
|
// 调用 API 获取数据
|
||||||
val jsonWx = JsonObject()
|
val jsonWx = JsonObject()
|
||||||
|
|
|
||||||
|
|
@ -5,9 +5,6 @@ import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.compose.runtime.State
|
import androidx.compose.runtime.State
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.lifecycle.viewModelScope
|
|
||||||
import com.img.rabbit.utils.WechatRequests
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import com.g.gysdk.GYManager
|
import com.g.gysdk.GYManager
|
||||||
import com.g.gysdk.GYResponse
|
import com.g.gysdk.GYResponse
|
||||||
import com.g.gysdk.GyCallBack
|
import com.g.gysdk.GyCallBack
|
||||||
|
|
@ -21,6 +18,7 @@ import com.img.rabbit.pages.screen.mine.setting.BindScreenType
|
||||||
import com.img.rabbit.provider.api.ApiManager
|
import com.img.rabbit.provider.api.ApiManager
|
||||||
import com.img.rabbit.provider.api.ResultVo
|
import com.img.rabbit.provider.api.ResultVo
|
||||||
import com.img.rabbit.provider.storage.PreferenceUtil
|
import com.img.rabbit.provider.storage.PreferenceUtil
|
||||||
|
import com.tencent.mm.opensdk.modelmsg.SendAuth
|
||||||
import com.tencent.mm.opensdk.openapi.IWXAPI
|
import com.tencent.mm.opensdk.openapi.IWXAPI
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
|
@ -29,7 +27,6 @@ class BindViewModel : BaseViewModel() {
|
||||||
private val TAG = "BindViewModel"
|
private val TAG = "BindViewModel"
|
||||||
private val ONEKEY_TAG = "BindViewModel_OneKey"
|
private val ONEKEY_TAG = "BindViewModel_OneKey"
|
||||||
var isBindWxAuthor = false
|
var isBindWxAuthor = false
|
||||||
private var isLaunchingWechat = false
|
|
||||||
val bindScreenType = mutableStateOf(BindScreenType.BIND_NORMAL)
|
val bindScreenType = mutableStateOf(BindScreenType.BIND_NORMAL)
|
||||||
// 登录状态
|
// 登录状态
|
||||||
val bindState = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
|
val bindState = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
|
||||||
|
|
@ -62,10 +59,6 @@ class BindViewModel : BaseViewModel() {
|
||||||
|
|
||||||
|
|
||||||
fun oneKeyLoginForGeTuiSdk(activity: Activity, onShowOneKeyScreen:(Boolean)->Unit) {
|
fun oneKeyLoginForGeTuiSdk(activity: Activity, onShowOneKeyScreen:(Boolean)->Unit) {
|
||||||
if (!PreferenceUtil.getAgreement()) {
|
|
||||||
onShowOneKeyScreen(false)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// 初始化 SDK
|
// 初始化 SDK
|
||||||
GYManager.getInstance().init(GyConfig.with(activity.applicationContext).callBack(object : GyCallBack {
|
GYManager.getInstance().init(GyConfig.with(activity.applicationContext).callBack(object : GyCallBack {
|
||||||
override fun onSuccess(response: GYResponse?) {
|
override fun onSuccess(response: GYResponse?) {
|
||||||
|
|
@ -213,20 +206,15 @@ class BindViewModel : BaseViewModel() {
|
||||||
|
|
||||||
//获取微信授权
|
//获取微信授权
|
||||||
private fun doWechatAuth(context: Context, wxApi: IWXAPI) {
|
private fun doWechatAuth(context: Context, wxApi: IWXAPI) {
|
||||||
if (isLaunchingWechat) return
|
if (!wxApi.isWXAppInstalled) {
|
||||||
isLaunchingWechat = true
|
CenterToast.show("您没有安装微信客户端,请先下载安装")
|
||||||
|
return
|
||||||
|
}
|
||||||
isBindWxAuthor = true
|
isBindWxAuthor = true
|
||||||
val state = context.packageName + java.util.UUID.randomUUID().toString()
|
val req = SendAuth.Req()
|
||||||
viewModelScope.launch {
|
req.scope = "snsapi_userinfo" // 只能填 snsapi_userinfo
|
||||||
try {
|
req.state = context.packageName + Math.random() * 1000 + "_phone"
|
||||||
WechatRequests.authorize(wxApi, state)?.let { message ->
|
wxApi.sendReq(req)
|
||||||
isBindWxAuthor = false
|
|
||||||
CenterToast.show(message)
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
isLaunchingWechat = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@ package com.img.rabbit.viewmodel
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.graphics.BitmapFactory
|
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
|
@ -13,12 +13,8 @@ import com.img.rabbit.utils.DownUtils
|
||||||
import com.img.rabbit.utils.FileUtils
|
import com.img.rabbit.utils.FileUtils
|
||||||
import com.img.rabbit.utils.ImageUtils
|
import com.img.rabbit.utils.ImageUtils
|
||||||
import com.img.rabbit.utils.PhotoCutter
|
import com.img.rabbit.utils.PhotoCutter
|
||||||
import com.img.rabbit.utils.imageSampleSize
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
|
||||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
|
@ -28,9 +24,6 @@ import kotlin.text.ifEmpty
|
||||||
|
|
||||||
|
|
||||||
class CutoutViewModel : BaseViewModel() {
|
class CutoutViewModel : BaseViewModel() {
|
||||||
companion object {
|
|
||||||
private const val MAX_IMAGE_DIMENSION = 2048
|
|
||||||
}
|
|
||||||
private val targetPath = FileUtils.instance?.cacheImageDir?.absolutePath?:""
|
private val targetPath = FileUtils.instance?.cacheImageDir?.absolutePath?:""
|
||||||
private val targetFileName = "cutoutCache.png"
|
private val targetFileName = "cutoutCache.png"
|
||||||
// 错误状态
|
// 错误状态
|
||||||
|
|
@ -39,51 +32,40 @@ class CutoutViewModel : BaseViewModel() {
|
||||||
// 本地抠图
|
// 本地抠图
|
||||||
fun cutoutImageFromLocal(context: Context, uri: Uri, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
|
fun cutoutImageFromLocal(context: Context, uri: Uri, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
|
||||||
// 执行抠图操作
|
// 执行抠图操作
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
Thread {
|
||||||
try {
|
|
||||||
val bitmap = ImageUtils.getBitmapFromUri(context, uri, MAX_IMAGE_DIMENSION)
|
|
||||||
?: throw IOException("无法获取图片")
|
|
||||||
try {
|
try {
|
||||||
|
val originalBitmap = ImageUtils.getBitmapFromUri(context, uri)
|
||||||
|
originalBitmap?.let { bitmap ->
|
||||||
PhotoCutter.cutPureHead(bitmap) { croppedBitmap ->
|
PhotoCutter.cutPureHead(bitmap) { croppedBitmap ->
|
||||||
bitmap.recycle()
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||||
deliverResult(croppedBitmap, onResult)
|
context.mainExecutor.execute {
|
||||||
|
onResult(true, croppedBitmap)
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
|
||||||
bitmap.recycle()
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e("CutoutViewModel", "本地抠图失败", e)
|
|
||||||
deliverResult(null, onResult)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
private fun deliverResult(bitmap: Bitmap?, onResult: (Boolean, Bitmap?) -> Unit) {
|
Log.e("CutoutScreen", "抠图失败: ${e.message}")
|
||||||
viewModelScope.launch(Dispatchers.Main) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||||
onResult(bitmap != null, bitmap)
|
context.mainExecutor.execute {
|
||||||
|
onResult(false, null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
//服务器抠图
|
//服务器抠图
|
||||||
fun cutoutImageFromService(context: Context, uri: Uri, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
|
fun cutoutImageFromService(context: Context, uri: Uri, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
|
||||||
// Always report failure so the screen can fall back to local segmentation, even offline.
|
mLaunch {
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
|
||||||
try {
|
try {
|
||||||
// 1. 获取并压缩图片为 PNG (.png/jpg/jpeg 只支持这三种格式,当前选择使用PNG)
|
// 1. 获取并压缩图片为 PNG (.png/jpg/jpeg 只支持这三种格式,当前选择使用PNG)
|
||||||
val bitmap = ImageUtils.getBitmapFromUri(context, uri, MAX_IMAGE_DIMENSION) ?: throw IOException("无法获取图片")
|
val bitmap = ImageUtils.getBitmapFromUri(context, uri) ?: throw IOException("无法获取图片")
|
||||||
val compressedBytes = try {
|
val outputStream = java.io.ByteArrayOutputStream()
|
||||||
java.io.ByteArrayOutputStream().use { outputStream ->
|
// PNG 是无损的,质量参数 100 即可
|
||||||
if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)) {
|
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
|
||||||
throw IOException("图片编码失败")
|
val compressedBytes = outputStream.toByteArray()
|
||||||
}
|
|
||||||
outputStream.toByteArray()
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
bitmap.recycle()
|
bitmap.recycle()
|
||||||
}
|
|
||||||
|
|
||||||
// 2. MediaType 修改为 image/png
|
// 2. MediaType 修改为 image/png
|
||||||
val requestFile = compressedBytes.toRequestBody("image/png".toMediaTypeOrNull(),0,compressedBytes.size)
|
val requestFile = compressedBytes.toRequestBody("image/png".toMediaTypeOrNull(),0,compressedBytes.size)
|
||||||
|
|
@ -97,56 +79,43 @@ class CutoutViewModel : BaseViewModel() {
|
||||||
val response = ApiManager.serviceVo.cutoutImage(filePart)
|
val response = ApiManager.serviceVo.cutoutImage(filePart)
|
||||||
|
|
||||||
if (response.status) {
|
if (response.status) {
|
||||||
Log.i("CutoutViewModel", "服务端抠图完成")
|
Log.i("CutoutViewModel", "抠图成功: ${response.data}")
|
||||||
// Preserve percent-encoding in signed download URLs.
|
val resultUrl = Uri.decode(response.data.toString())
|
||||||
val resultUrl = response.data as? String ?: throw IOException("抠图结果地址无效")
|
// 将 http 替换为 https
|
||||||
|
//val resultUrl = resultUrl.replace("http://", "https://")
|
||||||
saveUrlToCache(resultUrl, onResult)
|
saveUrlToCache(resultUrl, onResult)
|
||||||
} else {
|
} else {
|
||||||
withContext(Dispatchers.Main) {
|
|
||||||
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "抠图失败" })
|
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "抠图失败" })
|
||||||
|
onResult(false, null)
|
||||||
}
|
}
|
||||||
deliverResult(null, onResult)
|
|
||||||
}
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) { // 捕获更广泛的异常
|
} catch (e: Exception) { // 捕获更广泛的异常
|
||||||
Log.e("CutoutViewModel", "服务请求异常", e)
|
e.printStackTrace()
|
||||||
deliverResult(null, onResult)
|
Log.e("CutoutViewModel", "服务请求异常: ${e.message}")
|
||||||
|
onResult(false, null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun saveUrlToCache(url: String, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
|
private fun saveUrlToCache(url: String, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
|
||||||
try {
|
try {
|
||||||
require(url.toHttpUrlOrNull() != null) { "抠图结果地址无效" }
|
|
||||||
val targetFile = File(targetPath,targetFileName)
|
val targetFile = File(targetPath,targetFileName)
|
||||||
if(targetFile.exists()){
|
if(targetFile.exists()){
|
||||||
targetFile.delete()
|
targetFile.delete()
|
||||||
}
|
}
|
||||||
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
DownUtils.getInstance()
|
DownUtils.getInstance()
|
||||||
.initUrl(url, null)
|
.initUrl(url, null)
|
||||||
.setFilePath(targetPath)
|
.setFilePath(targetPath)
|
||||||
.setFileName(targetFileName)
|
.setFileName(targetFileName)
|
||||||
.setDownCallBack(object : DownUtils.DownCallBack {
|
.setDownCallBack(object : DownUtils.DownCallBack {
|
||||||
override fun success(file: File) {
|
override fun success(file: File) {
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
// 3. 下载成功后,将文件解析为 Bitmap 并回调给 UI
|
||||||
val bitmap = try {
|
val bitmap = android.graphics.BitmapFactory.decodeFile(file.absolutePath)
|
||||||
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
onResult(true, bitmap)
|
||||||
BitmapFactory.decodeFile(file.absolutePath, options)
|
|
||||||
options.inSampleSize = imageSampleSize(options.outWidth, options.outHeight, MAX_IMAGE_DIMENSION)
|
|
||||||
options.inJustDecodeBounds = false
|
|
||||||
BitmapFactory.decodeFile(file.absolutePath, options)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e("CutoutViewModel", "抠图结果读取失败", e)
|
|
||||||
null
|
|
||||||
}
|
|
||||||
deliverResult(bitmap, onResult)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun fail(str: String) {
|
override fun fail(str: String) {
|
||||||
deliverResult(null, onResult)
|
onResult(false, null)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun progress(position: Long) {
|
override fun progress(position: Long) {
|
||||||
|
|
@ -158,16 +127,14 @@ class CutoutViewModel : BaseViewModel() {
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun cancel() {
|
override fun cancel() {
|
||||||
deliverResult(null, onResult)
|
onResult(false, null)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.down()
|
.down()
|
||||||
} catch (e: CancellationException) {
|
}
|
||||||
throw e
|
|
||||||
}catch (e: Exception){
|
}catch (e: Exception){
|
||||||
Log.e("CutoutViewModel", "抠图结果下载失败", e)
|
e.printStackTrace()
|
||||||
deliverResult(null, onResult)
|
onResult(false, null)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -65,9 +65,9 @@ class FeedbackViewModel : BaseViewModel() {
|
||||||
fun uploadImage(context: Context, uri: Uri) {
|
fun uploadImage(context: Context, uri: Uri) {
|
||||||
mLaunch {
|
mLaunch {
|
||||||
try {
|
try {
|
||||||
val compressedUri:ByteArray = ImageUtils.imageCompressToUri(context, uri) ?: throw IOException("无法压缩图片")
|
val compressedUri = ImageUtils.imageCompressToUri(context, uri) ?: throw IOException("无法压缩图片")
|
||||||
val requestFile:RequestBody = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), compressedUri)
|
val requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), compressedUri)
|
||||||
val filePart:MultipartBody.Part = MultipartBody.Part.createFormData("file", uri.lastPathSegment, requestFile)
|
val filePart = MultipartBody.Part.createFormData("file", uri.lastPathSegment, requestFile)
|
||||||
val response = ApiManager.serviceVo.upload(filePart, "feedback")
|
val response = ApiManager.serviceVo.upload(filePart, "feedback")
|
||||||
if (response.status) {
|
if (response.status) {
|
||||||
val updateFile = FileManagerBean(response.data, uri)
|
val updateFile = FileManagerBean(response.data, uri)
|
||||||
|
|
|
||||||
|
|
@ -97,7 +97,6 @@ class GeneralViewModel: BaseViewModel(){
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun initWXApi(context: Context) {
|
private fun initWXApi(context: Context) {
|
||||||
if (!PreferenceUtil.getAgreement()) return
|
|
||||||
api = WXAPIFactory.createWXAPI(context, Constants.WxAppId, true)
|
api = WXAPIFactory.createWXAPI(context, Constants.WxAppId, true)
|
||||||
api.registerApp(Constants.WxAppId)
|
api.registerApp(Constants.WxAppId)
|
||||||
|
|
||||||
|
|
@ -119,10 +118,6 @@ class GeneralViewModel: BaseViewModel(){
|
||||||
override fun onCleared() {
|
override fun onCleared() {
|
||||||
super.onCleared()
|
super.onCleared()
|
||||||
connectivityManager.unregisterNetworkCallback(networkCallback)
|
connectivityManager.unregisterNetworkCallback(networkCallback)
|
||||||
if (::receiver.isInitialized && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
||||||
HeadParamUtils.applicationContext?.unregisterReceiver(receiver)
|
|
||||||
}
|
|
||||||
if (::api.isInitialized) api.detach()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(DelicateCoroutinesApi::class)
|
@OptIn(DelicateCoroutinesApi::class)
|
||||||
|
|
|
||||||
|
|
@ -35,13 +35,8 @@ import com.img.rabbit.utils.GlobalEventBus
|
||||||
import com.img.rabbit.utils.LoginBindEvent
|
import com.img.rabbit.utils.LoginBindEvent
|
||||||
import com.img.rabbit.utils.MMKVUtils
|
import com.img.rabbit.utils.MMKVUtils
|
||||||
import com.img.rabbit.utils.StringUtils
|
import com.img.rabbit.utils.StringUtils
|
||||||
import com.img.rabbit.utils.WechatRequests
|
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
|
||||||
|
|
@ -54,7 +49,6 @@ class LoginViewModel : BaseViewModel() {
|
||||||
|
|
||||||
private val ONEKEY_TAG = "OneKeyLoginViewModel"
|
private val ONEKEY_TAG = "OneKeyLoginViewModel"
|
||||||
var isLoginWxAuthor = false
|
var isLoginWxAuthor = false
|
||||||
private var isLaunchingWechat = false
|
|
||||||
val authInfoForAlipay: MutableState<String> = mutableStateOf("")
|
val authInfoForAlipay: MutableState<String> = mutableStateOf("")
|
||||||
|
|
||||||
val loginScreenType = mutableStateOf(LoginScreenType.LOGIN_NORMAL)
|
val loginScreenType = mutableStateOf(LoginScreenType.LOGIN_NORMAL)
|
||||||
|
|
@ -84,12 +78,8 @@ class LoginViewModel : BaseViewModel() {
|
||||||
val loginResult = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
|
val loginResult = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
|
||||||
// 用户配置获取结果
|
// 用户配置获取结果
|
||||||
val userConfigResult = mutableStateOf<ResultVo<UserConfigEntity>?>(null)
|
val userConfigResult = mutableStateOf<ResultVo<UserConfigEntity>?>(null)
|
||||||
// 保留最新配置供首页观察;userConfigResult 作为请求完成事件会被 Activity 清空。
|
// 用户信息获取结果
|
||||||
private val _userConfig = mutableStateOf(PreferenceUtil.getUserConfig())
|
val userInfoResult = mutableStateOf<ResultVo<UserInfoEntity>?>(null)
|
||||||
val userConfig: State<UserConfigEntity?> = _userConfig
|
|
||||||
// 页面直接观察用户数据,缓存只用于首次加载。
|
|
||||||
private val _userInfo = mutableStateOf(PreferenceUtil.getUserInfo())
|
|
||||||
val userInfo: State<UserInfoEntity?> = _userInfo
|
|
||||||
// 错误状态
|
// 错误状态
|
||||||
val errorState = mutableStateOf<ErrorBean?>(null)
|
val errorState = mutableStateOf<ErrorBean?>(null)
|
||||||
|
|
||||||
|
|
@ -118,7 +108,6 @@ class LoginViewModel : BaseViewModel() {
|
||||||
PreferenceUtil.saveXToken(response.data.token)
|
PreferenceUtil.saveXToken(response.data.token)
|
||||||
PreferenceUtil.setTimeDiff(response.data.nowtime.toLong() - System.currentTimeMillis() / 1000)
|
PreferenceUtil.setTimeDiff(response.data.nowtime.toLong() - System.currentTimeMillis() / 1000)
|
||||||
PreferenceUtil.saveUserConfig(response.data)
|
PreferenceUtil.saveUserConfig(response.data)
|
||||||
_userConfig.value = response.data
|
|
||||||
userConfigResult.value = response
|
userConfigResult.value = response
|
||||||
|
|
||||||
if(isInitConfig){
|
if(isInitConfig){
|
||||||
|
|
@ -141,55 +130,91 @@ class LoginViewModel : BaseViewModel() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 登录页进入时优先预取本机号码;失败、超时或结果无效时交由页面回退。 */
|
fun oneKeyLoginForGeTuiSdk(activity: Activity, onShowOneKeyScreen:(Boolean)->Unit) {
|
||||||
suspend fun prepareOneKeyLogin(activity: Activity): Boolean = withContext(Dispatchers.Main.immediate) {
|
// 初始化 SDK
|
||||||
oneKeyPreLogin = null
|
GYManager.getInstance().init(GyConfig.with(activity.applicationContext).callBack(object : GyCallBack {
|
||||||
isGYUIDValid.value = false
|
override fun onSuccess(response: GYResponse?) {
|
||||||
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) }
|
//预登录(提高拉起速度,可选但推荐)
|
||||||
?: return@withTimeoutOrNull false
|
GYManager.getInstance().ePreLogin(/* timeout = */ 8000, /* gyCallBack = */ object : GyCallBack {
|
||||||
val data = response.msg?.takeIf { it.isNotBlank() }
|
override fun onSuccess(response: GYResponse?) {
|
||||||
?: return@withTimeoutOrNull false
|
Log.i(ONEKEY_TAG, "--->预登录: onSuccess--->${response}")
|
||||||
val result = Json { ignoreUnknownKeys = true }.decodeFromString<OnekeyPreLogin>(data)
|
val preLoginData = response?.msg
|
||||||
if (result.errorCode != 0 || result.number.isBlank() ||
|
if (!preLoginData.isNullOrEmpty()) {
|
||||||
!manager.isPreLoginResultValid || manager.preLoginResult == null) {
|
try {
|
||||||
return@withTimeoutOrNull false
|
val json = Json { ignoreUnknownKeys = true }
|
||||||
|
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}")
|
||||||
}
|
}
|
||||||
oneKeyPreLogin = result
|
|
||||||
true
|
|
||||||
} ?: false
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
// 页面退出时取消等待,不让迟到的 SDK 回调切换后续页面。
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(ONEKEY_TAG, "一键登录准备失败,回退验证码登录", e)
|
Log.e(ONEKEY_TAG, "JSON解析失败: ${e.message}")
|
||||||
false
|
Log.e(ONEKEY_TAG, "原始数据: $preLoginData")
|
||||||
|
// 解析失败时继续执行原逻辑
|
||||||
|
onShowOneKeyScreen(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun awaitGyResponse(start: (GyCallBack) -> Unit): GYResponse? =
|
override fun onFailed(response: GYResponse?) {
|
||||||
suspendCancellableCoroutine { continuation ->
|
onShowOneKeyScreen(false)
|
||||||
val completed = AtomicBoolean(false)
|
Log.i(ONEKEY_TAG, "--->预登录: onFailed--->${response}")
|
||||||
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)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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}")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onFailed(response: GYResponse?) {
|
||||||
|
//预登录失败,提示用户稍后重试
|
||||||
|
onShowOneKeyScreen(false)
|
||||||
|
Log.i(ONEKEY_TAG, "--->预登录校验有效B: onFailed--->${response}")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun requestOneKeyLogin(gyuid: String, token: String) {
|
fun requestOneKeyLogin(gyuid: String, token: String) {
|
||||||
// 调用 API 获取数据
|
// 调用 API 获取数据
|
||||||
val jsonOneKey = JsonObject()
|
val jsonOneKey = JsonObject()
|
||||||
|
|
@ -244,20 +269,15 @@ class LoginViewModel : BaseViewModel() {
|
||||||
|
|
||||||
fun authorWechat(context: Context, wxApi:IWXAPI) {
|
fun authorWechat(context: Context, wxApi:IWXAPI) {
|
||||||
if (isPolicyAgreement.value) {
|
if (isPolicyAgreement.value) {
|
||||||
if (isLaunchingWechat) return
|
if (!wxApi.isWXAppInstalled) {
|
||||||
isLaunchingWechat = true
|
CenterToast.show("您没有安装微信客户端,请先下载安装")
|
||||||
|
return
|
||||||
|
}
|
||||||
isLoginWxAuthor = true
|
isLoginWxAuthor = true
|
||||||
val state = context.packageName + java.util.UUID.randomUUID().toString()
|
val req = SendAuth.Req()
|
||||||
viewModelScope.launch {
|
req.scope = "snsapi_userinfo" // 只能填 snsapi_userinfo
|
||||||
try {
|
req.state = context.packageName + Math.random() * 1000 + "_phone"
|
||||||
WechatRequests.authorize(wxApi, state)?.let { message ->
|
wxApi.sendReq(req)
|
||||||
isLoginWxAuthor = false
|
|
||||||
CenterToast.show(message)
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
isLaunchingWechat = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}else{
|
}else{
|
||||||
CenterToast.show("请先同意用户协议和隐私政策")
|
CenterToast.show("请先同意用户协议和隐私政策")
|
||||||
}
|
}
|
||||||
|
|
@ -392,18 +412,12 @@ class LoginViewModel : BaseViewModel() {
|
||||||
}
|
}
|
||||||
|
|
||||||
fun requestUserInfo(){
|
fun requestUserInfo(){
|
||||||
val currentUserId = _userConfig.value?.user_id
|
|
||||||
if (!currentUserId.isNullOrBlank() && _userInfo.value?.user_id != currentUserId) {
|
|
||||||
PreferenceUtil.saveUserInfo(null)
|
PreferenceUtil.saveUserInfo(null)
|
||||||
_userInfo.value = null
|
|
||||||
}
|
|
||||||
mLaunch {
|
mLaunch {
|
||||||
val response = ApiManager.serviceVo.userInfo()
|
val response = ApiManager.serviceVo.userInfo()
|
||||||
// 切换账号后,忽略旧账号尚未完成的请求。
|
|
||||||
if (currentUserId != _userConfig.value?.user_id) return@mLaunch
|
|
||||||
if(response.status){
|
if(response.status){
|
||||||
PreferenceUtil.saveUserInfo(response.data)
|
PreferenceUtil.saveUserInfo(response.data)
|
||||||
_userInfo.value = response.data
|
userInfoResult.value = response
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -418,7 +432,6 @@ class LoginViewModel : BaseViewModel() {
|
||||||
val response = ApiManager.serviceVo.logout()
|
val response = ApiManager.serviceVo.logout()
|
||||||
if (response.status) {
|
if (response.status) {
|
||||||
PreferenceUtil.clearLogin()
|
PreferenceUtil.clearLogin()
|
||||||
_userInfo.value = null
|
|
||||||
AppEventBus.post( LoginBindEvent.Login(userId = null, loginType = PreferenceUtil.getLoginType(), isLogin = false, data = null) )
|
AppEventBus.post( LoginBindEvent.Login(userId = null, loginType = PreferenceUtil.getLoginType(), isLogin = false, data = null) )
|
||||||
} else {
|
} else {
|
||||||
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "退出登录失败" })
|
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "退出登录失败" })
|
||||||
|
|
|
||||||
|
|
@ -1,43 +1,30 @@
|
||||||
package com.img.rabbit.viewmodel
|
package com.img.rabbit.viewmodel
|
||||||
|
|
||||||
import android.util.Log
|
import com.img.rabbit.bean.response.ServiceWxLinkEntity
|
||||||
import androidx.lifecycle.viewModelScope
|
|
||||||
import com.img.rabbit.components.CenterToast
|
|
||||||
import com.img.rabbit.utils.WechatRequests
|
|
||||||
import com.img.rabbit.provider.api.ApiManager
|
import com.img.rabbit.provider.api.ApiManager
|
||||||
|
import com.tencent.mm.opensdk.constants.Build
|
||||||
|
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat
|
||||||
import com.tencent.mm.opensdk.openapi.IWXAPI
|
import com.tencent.mm.opensdk.openapi.IWXAPI
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
|
|
||||||
class MineViewModel : BaseViewModel() {
|
class MineViewModel : BaseViewModel() {
|
||||||
private var isOpeningService = false
|
private val TAG = "MineViewModel"
|
||||||
|
|
||||||
//请求客服连接
|
//请求客服连接
|
||||||
fun requestServiceLink(api: IWXAPI){
|
fun requestServiceLink(api: IWXAPI){
|
||||||
if (isOpeningService) return
|
mLaunch {
|
||||||
isOpeningService = true
|
|
||||||
viewModelScope.launch {
|
|
||||||
try {
|
|
||||||
val message = withContext(Dispatchers.IO) {
|
|
||||||
if (!api.isWXAppInstalled) return@withContext "未安装微信客户端"
|
|
||||||
val response = ApiManager.serviceVo.wxService()
|
val response = ApiManager.serviceVo.wxService()
|
||||||
if (!response.status) {
|
if (response.status) {
|
||||||
return@withContext "暂时无法获取客服信息,请稍后重试"
|
contactClientService(response.data, api)
|
||||||
}
|
|
||||||
val data = response.data
|
|
||||||
WechatRequests.customerService(api, data?.corpid, data?.address)
|
|
||||||
}
|
|
||||||
message?.let { CenterToast.show(it) }
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e("MineViewModel", "打开微信客服失败", e)
|
|
||||||
CenterToast.show("打开客服失败,请检查网络后重试")
|
|
||||||
} finally {
|
|
||||||
isOpeningService = false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun contactClientService(data: ServiceWxLinkEntity, api: IWXAPI) {
|
||||||
|
if (api.wxAppSupportAPI >= Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
|
||||||
|
val req = WXOpenCustomerServiceChat.Req()
|
||||||
|
req.corpId = data.corpid
|
||||||
|
req.url = data.address
|
||||||
|
api.sendReq(req)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,31 +1,20 @@
|
||||||
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){
|
//请求客服连接
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
fun requestReport(requst: ReportRequest){
|
||||||
try {
|
mLaunch {
|
||||||
val body = Json.encodeToString(request)
|
val requstJson = Json.encodeToString(requst)
|
||||||
.toRequestBody("application/json; charset=utf-8".toMediaType())
|
val response = ApiManager.serviceVo.report(requstJson.toRequestBody())
|
||||||
ApiManager.serviceVo.report(body)
|
Log.i(TAG, "requestReport: ${response.data}")
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
|
||||||
// 上报失败不干扰下载重试和启动界面。
|
|
||||||
Log.w(TAG, "事件上报失败", e)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,61 +1,41 @@
|
||||||
|
@file:OptIn(DelicateCoroutinesApi::class)
|
||||||
|
|
||||||
package com.img.rabbit.wxapi
|
package com.img.rabbit.wxapi
|
||||||
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.util.Log
|
|
||||||
import com.img.rabbit.utils.AppEventBus
|
import com.img.rabbit.utils.AppEventBus
|
||||||
import com.img.rabbit.utils.WXAuthEvent
|
import com.img.rabbit.utils.WXAuthEvent
|
||||||
import com.img.rabbit.utils.wechatAuthResult
|
|
||||||
import com.tencent.mm.opensdk.constants.ConstantsAPI
|
import com.tencent.mm.opensdk.constants.ConstantsAPI
|
||||||
import com.tencent.mm.opensdk.modelbase.BaseResp
|
import com.tencent.mm.opensdk.modelbase.BaseResp
|
||||||
import com.tencent.mm.opensdk.modelmsg.SendAuth
|
import com.tencent.mm.opensdk.modelmsg.SendAuth
|
||||||
import com.umeng.socialize.weixin.view.WXCallbackActivity
|
import com.umeng.socialize.weixin.view.WXCallbackActivity
|
||||||
|
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||||
|
import kotlinx.coroutines.GlobalScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
|
||||||
class WXEntryActivity : WechatConsentActivity() {
|
class WXEntryActivity : WXCallbackActivity() {
|
||||||
override val callbackClassName = "com.img.rabbit.wxapi.AuthorizedWXEntryActivity"
|
|
||||||
}
|
|
||||||
|
|
||||||
class AuthorizedWXEntryActivity : WXCallbackActivity() {
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
try {
|
|
||||||
// The SDK dispatches handleIntent/onResp synchronously.
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e("WXEntryActivity", "微信回调处理失败", e)
|
|
||||||
AppEventBus.tryPost(WXAuthEvent.AuthFailure("微信授权失败,请重试"))
|
|
||||||
} finally {
|
|
||||||
// Invalid intents may not invoke onResp at all.
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
|
||||||
try {
|
|
||||||
super.onNewIntent(intent)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e("WXEntryActivity", "微信回调处理失败", e)
|
|
||||||
AppEventBus.tryPost(WXAuthEvent.AuthFailure("微信授权失败,请重试"))
|
|
||||||
} finally {
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onResp(resp: BaseResp?) {
|
override fun onResp(resp: BaseResp?) {
|
||||||
try {
|
|
||||||
if (resp?.type == ConstantsAPI.COMMAND_SENDAUTH) {
|
if (resp?.type == ConstantsAPI.COMMAND_SENDAUTH) {
|
||||||
val event = wechatAuthResult(resp.errCode, (resp as? SendAuth.Resp)?.code)
|
when (resp.errCode) {
|
||||||
if (!AppEventBus.tryPost(event)) {
|
BaseResp.ErrCode.ERR_OK -> {
|
||||||
Log.w("WXEntryActivity", "微信授权结果未能投递")
|
val authResp = resp as SendAuth.Resp
|
||||||
}
|
//val wxState = WxBean(code = authResp.code,state = authResp.state)
|
||||||
} else {
|
|
||||||
super.onResp(resp)
|
GlobalScope.launch {
|
||||||
}
|
//GlobalStateManager(this@WXEntryActivity).storeGlobalWxAuthorization(authResp.code)
|
||||||
} catch (e: Exception) {
|
AppEventBus.post(
|
||||||
Log.e("WXEntryActivity", "微信授权回调异常", e)
|
WXAuthEvent.AuthResult(
|
||||||
AppEventBus.tryPost(WXAuthEvent.AuthFailure("微信授权失败,请重试"))
|
code = authResp.code,
|
||||||
} finally {
|
authType = 0
|
||||||
|
)
|
||||||
|
)
|
||||||
finish()
|
finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -10,11 +10,7 @@ import com.tencent.mm.opensdk.modelbase.BaseReq
|
||||||
import com.tencent.mm.opensdk.modelbase.BaseResp
|
import com.tencent.mm.opensdk.modelbase.BaseResp
|
||||||
import io.dcloud.feature.payment.weixin.AbsWXPayCallbackActivity
|
import io.dcloud.feature.payment.weixin.AbsWXPayCallbackActivity
|
||||||
|
|
||||||
class WXPayEntryActivity : WechatConsentActivity() {
|
class WXPayEntryActivity : AbsWXPayCallbackActivity() {
|
||||||
override val callbackClassName = "com.img.rabbit.wxapi.AuthorizedWXPayEntryActivity"
|
|
||||||
}
|
|
||||||
|
|
||||||
class AuthorizedWXPayEntryActivity : AbsWXPayCallbackActivity() {
|
|
||||||
//val scope = CoroutineScope(Dispatchers.Main)
|
//val scope = CoroutineScope(Dispatchers.Main)
|
||||||
private lateinit var generalViewModel: GeneralViewModel
|
private lateinit var generalViewModel: GeneralViewModel
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
package com.img.rabbit.wxapi
|
|
||||||
|
|
||||||
import android.app.Activity
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Bundle
|
|
||||||
import com.img.rabbit.provider.storage.PrivacyConsentStore
|
|
||||||
|
|
||||||
/** 外部回调先经过原生 Activity,避免 SDK 父类在未授权时执行 onCreate。 */
|
|
||||||
abstract class WechatConsentActivity : Activity() {
|
|
||||||
protected abstract val callbackClassName: String
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
dispatch(intent)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
|
||||||
super.onNewIntent(intent)
|
|
||||||
dispatch(intent)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun dispatch(callback: Intent) {
|
|
||||||
if (PrivacyConsentStore.isAccepted()) {
|
|
||||||
startActivity(Intent(callback).setClassName(this, callbackClassName))
|
|
||||||
}
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -6,7 +6,6 @@
|
||||||
See https://developer.android.com/about/versions/12/backup-restore
|
See https://developer.android.com/about/versions/12/backup-restore
|
||||||
-->
|
-->
|
||||||
<full-backup-content>
|
<full-backup-content>
|
||||||
<exclude domain="sharedpref" path="privacy_consent.xml" />
|
|
||||||
<!--
|
<!--
|
||||||
<include domain="sharedpref" path="."/>
|
<include domain="sharedpref" path="."/>
|
||||||
<exclude domain="sharedpref" path="device.xml"/>
|
<exclude domain="sharedpref" path="device.xml"/>
|
||||||
|
|
|
||||||
|
|
@ -5,15 +5,11 @@
|
||||||
-->
|
-->
|
||||||
<data-extraction-rules>
|
<data-extraction-rules>
|
||||||
<cloud-backup>
|
<cloud-backup>
|
||||||
<exclude domain="sharedpref" path="privacy_consent.xml" />
|
|
||||||
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
||||||
<include .../>
|
<include .../>
|
||||||
<exclude .../>
|
<exclude .../>
|
||||||
-->
|
-->
|
||||||
</cloud-backup>
|
</cloud-backup>
|
||||||
<device-transfer>
|
|
||||||
<exclude domain="sharedpref" path="privacy_consent.xml" />
|
|
||||||
</device-transfer>
|
|
||||||
<!--
|
<!--
|
||||||
<device-transfer>
|
<device-transfer>
|
||||||
<include .../>
|
<include .../>
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,7 @@
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<network-security-config>
|
<network-security-config>
|
||||||
<base-config cleartextTrafficPermitted="true" />
|
<domain-config cleartextTrafficPermitted="true">
|
||||||
<!-- <domain-config cleartextTrafficPermitted="true">-->
|
<domain includeSubdomains="true">enrichgw.10010.com</domain>
|
||||||
<!-- <domain includeSubdomains="true">enrichgw.10010.com</domain>-->
|
<domain includeSubdomains="true">aliyuncs.com</domain>
|
||||||
<!-- <domain includeSubdomains="true">aliyuncs.com</domain>-->
|
</domain-config>
|
||||||
<!-- <domain includeSubdomains="true">home.batiao8.com</domain>-->
|
|
||||||
<!-- </domain-config>-->
|
|
||||||
</network-security-config>
|
</network-security-config>
|
||||||
|
|
@ -1,23 +1,5 @@
|
||||||
pluginManagement {
|
pluginManagement {
|
||||||
repositories {
|
repositories {
|
||||||
maven {
|
|
||||||
name = "batiao"
|
|
||||||
url = uri("http://proxy.local:7777/repository/maven-releases/")
|
|
||||||
isAllowInsecureProtocol = true
|
|
||||||
content { includeGroup("com.batiao") }
|
|
||||||
credentials {
|
|
||||||
val local = java.util.Properties().apply {
|
|
||||||
val propertiesFile = file("local.properties")
|
|
||||||
if (propertiesFile.exists()) propertiesFile.inputStream().use { load(it) }
|
|
||||||
}
|
|
||||||
username = providers.gradleProperty("BATIAO_MAVEN_USERNAME")
|
|
||||||
.orElse(providers.environmentVariable("BATIAO_MAVEN_USERNAME"))
|
|
||||||
.orNull ?: local.getProperty("BATIAO_MAVEN_USERNAME")
|
|
||||||
password = providers.gradleProperty("BATIAO_MAVEN_PASSWORD")
|
|
||||||
.orElse(providers.environmentVariable("BATIAO_MAVEN_PASSWORD"))
|
|
||||||
.orNull ?: local.getProperty("BATIAO_MAVEN_PASSWORD")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
google {
|
google {
|
||||||
content {
|
content {
|
||||||
includeGroupByRegex("com\\.android.*")
|
includeGroupByRegex("com\\.android.*")
|
||||||
|
|
@ -32,36 +14,11 @@ pluginManagement {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
gradlePluginPortal()
|
gradlePluginPortal()
|
||||||
}
|
}
|
||||||
resolutionStrategy {
|
|
||||||
eachPlugin {
|
|
||||||
if (requested.id.id == "com.batiao.batiaosdkbuilder") {
|
|
||||||
useModule("com.batiao:batiao-sdk-builder:${requested.version}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@Suppress("UnstableApiUsage")
|
@Suppress("UnstableApiUsage")
|
||||||
dependencyResolutionManagement {
|
dependencyResolutionManagement {
|
||||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
repositories {
|
repositories {
|
||||||
maven {
|
|
||||||
name = "batiao"
|
|
||||||
url = uri("http://proxy.local:7777/repository/maven-releases/")
|
|
||||||
isAllowInsecureProtocol = true
|
|
||||||
content { includeGroup("com.batiao") }
|
|
||||||
credentials {
|
|
||||||
val local = java.util.Properties().apply {
|
|
||||||
val propertiesFile = file("local.properties")
|
|
||||||
if (propertiesFile.exists()) propertiesFile.inputStream().use { load(it) }
|
|
||||||
}
|
|
||||||
username = providers.gradleProperty("BATIAO_MAVEN_USERNAME")
|
|
||||||
.orElse(providers.environmentVariable("BATIAO_MAVEN_USERNAME"))
|
|
||||||
.orNull ?: local.getProperty("BATIAO_MAVEN_USERNAME")
|
|
||||||
password = providers.gradleProperty("BATIAO_MAVEN_PASSWORD")
|
|
||||||
.orElse(providers.environmentVariable("BATIAO_MAVEN_PASSWORD"))
|
|
||||||
.orNull ?: local.getProperty("BATIAO_MAVEN_PASSWORD")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
google()
|
google()
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
flatDir {
|
flatDir {
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue