1、解决微信登录和客服可能的ANR问题
2、解决抠图时可能的崩溃问题
This commit is contained in:
Elemt 2026-11-10 10:11:06 +08:00
parent 158b71fa5e
commit 00aebd8b86
15 changed files with 367 additions and 180 deletions

View File

@ -118,6 +118,12 @@ fun LoginScreen(navController: NavHostController? = null, generalViewModel: Gene
loginViewModel.isLoginWxAuthor = false
}
}
is WXAuthEvent.AuthFailure -> {
if (loginViewModel.isLoginWxAuthor) {
loginViewModel.isLoginWxAuthor = false
CenterToast.show(event.message)
}
}
}
}
}

View File

@ -399,11 +399,7 @@ fun MineScreen(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
if (!generalViewModel.api.isWXAppInstalled) {
CenterToast.show("未安装微信客户端")
}else if(userInfo != null){
viewModel.requestServiceLink(generalViewModel.api)
}
viewModel.requestServiceLink(generalViewModel.api)
},
verticalAlignment = Alignment.CenterVertically
) {

View File

@ -78,7 +78,6 @@ import coil3.compose.AsyncImage
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import com.img.rabbit.R
import com.img.rabbit.bean.local.ClothingBean
import com.img.rabbit.bean.local.HairstyleBean
@ -102,7 +101,10 @@ import java.util.Date
import java.util.Locale
import com.img.rabbit.utils.PhotoCutter
import com.img.rabbit.viewmodel.CutoutViewModel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
// 建议的状态数据结构
@ -146,8 +148,10 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
val coroutineScope = rememberCoroutineScope()
// 抠图加载中状态
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") ?: 23f
val widthParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("width") ?: 25f
val heightParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("height") ?: 35f
//显示服装和发型
@ -188,7 +192,7 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
// 当前选中的发型
val selectedHairstyle = remember { mutableStateOf(hairstyleForFemales.getOrNull(0)) }
// 当前选中的尺寸
val selectedSize = remember { mutableStateOf(resizes.first { it.width == widthParam && it.height == heightParam }) }
val selectedSize = remember { mutableStateOf(resizes.firstOrNull { it.width == widthParam && it.height == heightParam } ?: resizes.first()) }
val storagePermissionState = rememberPermissionState(
@ -207,6 +211,8 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
) { uri ->
uri?.let {
selectedImageUri.value = it
cutoutResultBitmap.value = null
recordedImage = null
isLoading.value = true
// 执行抠图操作
if(isLoadingCutoutMethodFromService){
@ -290,54 +296,47 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
.navigationBarsPadding()
) {
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 {
// 从 Layer 捕获 Bitmap
val bitmap = graphicsLayer.toImageBitmap().asAndroidBitmap()
// 保存图片到系统相册(图片已按比例裁剪)
/*
saveCanvasToGallery(context, bitmap, ExportFormat.JPG){fileName, isSuccess ->
val tips = if(isSuccess){ "已保存为: $fileName" }else{ "保存失败" }
CenterToast.show(tips)
}
*/
/*
// 保存图片到系统相册(指定尺寸,如果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)
try {
val bitmap = graphicsLayer.toImageBitmap().asAndroidBitmap()
try {
val result = withContext(Dispatchers.IO) {
var result: Pair<String, Boolean> = "" to false
saveCanvasToGallery(context, bitmap, ExportFormat.JPG) { filename, success ->
result = filename to success
}
result
}
// 情况 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
}
}
}
@ -398,6 +397,7 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
graphicsLayer.record {
this@drawWithContent.drawContent()
}
recordedImage = cutoutResultBitmap.value
drawLayer(graphicsLayer)
}
.clipToBounds()

View File

@ -98,6 +98,12 @@ fun BindScreen(navController: NavHostController, viewModel: BindViewModel = view
viewModel.isBindWxAuthor = false
}
}
is WXAuthEvent.AuthFailure -> {
if (viewModel.isBindWxAuthor) {
viewModel.isBindWxAuthor = false
CenterToast.show(event.message)
}
}
}
}
}
@ -1042,4 +1048,4 @@ enum class BindScreenType {
@Composable
private fun PreviewBindScreen(){
BindScreen(navController = rememberNavController(), generalViewModel = viewModel(),viewModel = viewModel(), bindType = BindViewModel.BindType.FROM_PHONE.type)
}
}

View File

@ -13,7 +13,7 @@ object AppEventBus {
)
val events = _events.asSharedFlow()
*/
private val _events = MutableSharedFlow<Any>()
private val _events = MutableSharedFlow<Any>(extraBufferCapacity = 16)
val events = _events.asSharedFlow()
suspend fun post(event: UniMpWXPayEvent) {
@ -27,6 +27,9 @@ object AppEventBus {
suspend fun post(event: WXAuthEvent) {
_events.emit(event)
}
// Callback Activities must close even when a subscriber is temporarily busy.
fun tryPost(event: WXAuthEvent): Boolean = _events.tryEmit(event)
}
/**
@ -53,6 +56,7 @@ sealed class LoginBindEvent {
*/
sealed class WXAuthEvent {
data class AuthResult(val code: String, val authType: Int) : WXAuthEvent()
data class AuthFailure(val message: String) : WXAuthEvent()
}
/**

View File

@ -0,0 +1,12 @@
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
}

View File

@ -205,10 +205,19 @@ object ImageUtils {
* @param uri 图片URI
* @return Bitmap对象,如果获取失败则返回null
*/
fun getBitmapFromUri(context: Context, uri: Uri): Bitmap? {
fun getBitmapFromUri(context: Context, uri: Uri, maxDimension: Int? = null): Bitmap? {
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 ->
BitmapFactory.decodeStream(inputStream)
BitmapFactory.decodeStream(inputStream, null, options)
}
} catch (e: Exception) {
Log.e("ImageUtils", "从URI获取Bitmap失败", e)

View File

@ -1,12 +1,14 @@
package com.img.rabbit.utils
import android.graphics.*
import android.util.Log
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.segmentation.Segmentation
import com.google.mlkit.vision.segmentation.selfie.SelfieSegmenterOptions
import androidx.core.graphics.createBitmap
import androidx.compose.ui.geometry.Offset
import java.util.concurrent.Executors
// 变换状态模型
data class TransformState(
@ -18,6 +20,7 @@ data class TransformState(
object PhotoCutter {
private val executor = Executors.newSingleThreadExecutor()
fun cutPureHead(sourceBitmap: Bitmap, callback: (Bitmap?) -> Unit) {
// 1. 配置分割器:单图模式
@ -25,29 +28,42 @@ object PhotoCutter {
.setDetectorMode(SelfieSegmenterOptions.SINGLE_IMAGE_MODE)
.build()
val segmenter = Segmentation.getClient(options)
val image = InputImage.fromBitmap(sourceBitmap, 0)
// 2. 开始处理
segmenter.process(image)
.addOnSuccessListener { mask ->
val resultBitmap = generateTransparentBitmap(sourceBitmap, mask.buffer)
callback(resultBitmap)
}
.addOnFailureListener {
callback(null)
try {
val image = InputImage.fromBitmap(sourceBitmap, 0)
// Mask conversion belongs off the UI thread; exceptions here are asynchronous.
segmenter.process(image).addOnCompleteListener(executor) { task ->
val result = try {
val mask = task.result
generateTransparentBitmap(sourceBitmap, mask.buffer, mask.width, mask.height)
} catch (e: Exception) {
Log.e("PhotoCutter", "本地抠图失败", e)
null
} finally {
segmenter.close()
}
callback(result)
}
} catch (e: Exception) {
segmenter.close()
throw e
}
}
private fun generateTransparentBitmap(
source: Bitmap,
maskBuffer: java.nio.ByteBuffer,
maskWidth: Int,
maskHeight: Int,
): Bitmap {
val width = source.width
val height = source.height
val result = createBitmap(width, height)
// 将掩码缓冲区重置
maskBuffer.rewind()
require(maskWidth > 0 && maskHeight > 0 &&
maskBuffer.remaining().toLong() >= maskWidth.toLong() * maskHeight * 4) {
"无效的人像掩码"
}
// 逐像素处理
val pixels = IntArray(width * height)
@ -55,7 +71,9 @@ object PhotoCutter {
for (i in 0 until width * height) {
// 获取当前像素的人像概率(0.0 ~ 1.0)
val confidence = maskBuffer.float
val maskX = (i % width).toLong() * maskWidth / width
val maskY = (i / width).toLong() * maskHeight / height
val confidence = maskBuffer.getFloat(((maskY * maskWidth + maskX) * 4).toInt())
// 如果置信度低于 0.5,认为该像素是背景,设为完全透明
if (confidence < 0.5) {
@ -63,6 +81,7 @@ object PhotoCutter {
}
}
val result = createBitmap(width, height)
result.setPixels(pixels, 0, width, 0, 0, width, height)
return result
}

View File

@ -0,0 +1,13 @@
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("微信授权失败,请重试")
}

View File

@ -0,0 +1,46 @@
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) {
"微信暂时无法响应,请稍后重试"
}
}
}

View File

@ -5,6 +5,9 @@ import android.content.Context
import android.util.Log
import androidx.compose.runtime.State
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.GYResponse
import com.g.gysdk.GyCallBack
@ -18,7 +21,6 @@ import com.img.rabbit.pages.screen.mine.setting.BindScreenType
import com.img.rabbit.provider.api.ApiManager
import com.img.rabbit.provider.api.ResultVo
import com.img.rabbit.provider.storage.PreferenceUtil
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import kotlinx.serialization.json.Json
import okhttp3.RequestBody.Companion.toRequestBody
@ -27,6 +29,7 @@ class BindViewModel : BaseViewModel() {
private val TAG = "BindViewModel"
private val ONEKEY_TAG = "BindViewModel_OneKey"
var isBindWxAuthor = false
private var isLaunchingWechat = false
val bindScreenType = mutableStateOf(BindScreenType.BIND_NORMAL)
// 登录状态
val bindState = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
@ -206,15 +209,20 @@ class BindViewModel : BaseViewModel() {
//获取微信授权
private fun doWechatAuth(context: Context, wxApi: IWXAPI) {
if (!wxApi.isWXAppInstalled) {
CenterToast.show("您没有安装微信客户端,请先下载安装")
return
}
if (isLaunchingWechat) return
isLaunchingWechat = true
isBindWxAuthor = true
val req = SendAuth.Req()
req.scope = "snsapi_userinfo" // 只能填 snsapi_userinfo
req.state = context.packageName + Math.random() * 1000 + "_phone"
wxApi.sendReq(req)
val state = context.packageName + java.util.UUID.randomUUID().toString()
viewModelScope.launch {
try {
WechatRequests.authorize(wxApi, state)?.let { message ->
isBindWxAuthor = false
CenterToast.show(message)
}
} finally {
isLaunchingWechat = false
}
}
}
/**
@ -257,4 +265,4 @@ class BindViewModel : BaseViewModel() {
FROM_PHONE(0,"手机号"),
FROM_WX(1,"微信")
}
}
}

View File

@ -2,8 +2,8 @@ package com.img.rabbit.viewmodel
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
@ -13,8 +13,12 @@ import com.img.rabbit.utils.DownUtils
import com.img.rabbit.utils.FileUtils
import com.img.rabbit.utils.ImageUtils
import com.img.rabbit.utils.PhotoCutter
import com.img.rabbit.utils.imageSampleSize
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody
@ -24,6 +28,9 @@ import kotlin.text.ifEmpty
class CutoutViewModel : BaseViewModel() {
companion object {
private const val MAX_IMAGE_DIMENSION = 2048
}
private val targetPath = FileUtils.instance?.cacheImageDir?.absolutePath?:""
private val targetFileName = "cutoutCache.png"
// 错误状态
@ -32,40 +39,51 @@ class CutoutViewModel : BaseViewModel() {
// 本地抠图
fun cutoutImageFromLocal(context: Context, uri: Uri, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
// 执行抠图操作
Thread {
viewModelScope.launch(Dispatchers.IO) {
try {
val originalBitmap = ImageUtils.getBitmapFromUri(context, uri)
originalBitmap?.let { bitmap ->
val bitmap = ImageUtils.getBitmapFromUri(context, uri, MAX_IMAGE_DIMENSION)
?: throw IOException("无法获取图片")
try {
PhotoCutter.cutPureHead(bitmap) { croppedBitmap ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
context.mainExecutor.execute {
onResult(true, croppedBitmap)
}
}
bitmap.recycle()
deliverResult(croppedBitmap, onResult)
}
} catch (e: Exception) {
bitmap.recycle()
throw e
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e("CutoutScreen", "抠图失败: ${e.message}")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
context.mainExecutor.execute {
onResult(false, null)
}
}
Log.e("CutoutViewModel", "本地抠图失败", e)
deliverResult(null, onResult)
}
}.start()
}
}
private fun deliverResult(bitmap: Bitmap?, onResult: (Boolean, Bitmap?) -> Unit) {
viewModelScope.launch(Dispatchers.Main) {
onResult(bitmap != null, bitmap)
}
}
//服务器抠图
fun cutoutImageFromService(context: Context, uri: Uri, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
mLaunch {
// Always report failure so the screen can fall back to local segmentation, even offline.
viewModelScope.launch(Dispatchers.IO) {
try {
// 1. 获取并压缩图片为 PNG (.png/jpg/jpeg 只支持这三种格式,当前选择使用PNG)
val bitmap = ImageUtils.getBitmapFromUri(context, uri) ?: throw IOException("无法获取图片")
val outputStream = java.io.ByteArrayOutputStream()
// PNG 是无损的,质量参数 100 即可
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
val compressedBytes = outputStream.toByteArray()
bitmap.recycle()
val bitmap = ImageUtils.getBitmapFromUri(context, uri, MAX_IMAGE_DIMENSION) ?: throw IOException("无法获取图片")
val compressedBytes = try {
java.io.ByteArrayOutputStream().use { outputStream ->
if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)) {
throw IOException("图片编码失败")
}
outputStream.toByteArray()
}
} finally {
bitmap.recycle()
}
// 2. MediaType 修改为 image/png
val requestFile = compressedBytes.toRequestBody("image/png".toMediaTypeOrNull(),0,compressedBytes.size)
@ -79,43 +97,56 @@ class CutoutViewModel : BaseViewModel() {
val response = ApiManager.serviceVo.cutoutImage(filePart)
if (response.status) {
Log.i("CutoutViewModel", "抠图成功: ${response.data}")
val resultUrl = Uri.decode(response.data.toString())
// 将 http 替换为 https
//val resultUrl = resultUrl.replace("http://", "https://")
Log.i("CutoutViewModel", "服务端抠图完成")
// Preserve percent-encoding in signed download URLs.
val resultUrl = response.data as? String ?: throw IOException("抠图结果地址无效")
saveUrlToCache(resultUrl, onResult)
} else {
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "抠图失败" })
onResult(false, null)
withContext(Dispatchers.Main) {
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "抠图失败" })
}
deliverResult(null, onResult)
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { // 捕获更广泛的异常
e.printStackTrace()
Log.e("CutoutViewModel", "服务请求异常: ${e.message}")
onResult(false, null)
Log.e("CutoutViewModel", "服务请求异常", e)
deliverResult(null, onResult)
}
}
}
private fun saveUrlToCache(url: String, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
try {
val targetFile = File(targetPath,targetFileName)
if(targetFile.exists()){
targetFile.delete()
}
viewModelScope.launch(Dispatchers.IO) {
viewModelScope.launch(Dispatchers.IO) {
try {
require(url.toHttpUrlOrNull() != null) { "抠图结果地址无效" }
val targetFile = File(targetPath, targetFileName)
if (targetFile.exists()) {
targetFile.delete()
}
DownUtils.getInstance()
.initUrl(url, null)
.setFilePath(targetPath)
.setFileName(targetFileName)
.setDownCallBack(object : DownUtils.DownCallBack {
override fun success(file: File) {
// 3. 下载成功后,将文件解析为 Bitmap 并回调给 UI
val bitmap = android.graphics.BitmapFactory.decodeFile(file.absolutePath)
onResult(true, bitmap)
viewModelScope.launch(Dispatchers.IO) {
val bitmap = try {
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
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) {
onResult(false, null)
deliverResult(null, onResult)
}
override fun progress(position: Long) {
@ -127,14 +158,16 @@ class CutoutViewModel : BaseViewModel() {
}
override fun cancel() {
onResult(false, null)
deliverResult(null, onResult)
}
})
.down()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e("CutoutViewModel", "抠图结果下载失败", e)
deliverResult(null, onResult)
}
}catch (e: Exception){
e.printStackTrace()
onResult(false, null)
}
}
}
}

View File

@ -35,7 +35,7 @@ import com.img.rabbit.utils.GlobalEventBus
import com.img.rabbit.utils.LoginBindEvent
import com.img.rabbit.utils.MMKVUtils
import com.img.rabbit.utils.StringUtils
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.img.rabbit.utils.WechatRequests
import com.tencent.mm.opensdk.openapi.IWXAPI
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.suspendCancellableCoroutine
@ -54,6 +54,7 @@ class LoginViewModel : BaseViewModel() {
private val ONEKEY_TAG = "OneKeyLoginViewModel"
var isLoginWxAuthor = false
private var isLaunchingWechat = false
val authInfoForAlipay: MutableState<String> = mutableStateOf("")
val loginScreenType = mutableStateOf(LoginScreenType.LOGIN_NORMAL)
@ -243,15 +244,20 @@ class LoginViewModel : BaseViewModel() {
fun authorWechat(context: Context, wxApi:IWXAPI) {
if (isPolicyAgreement.value) {
if (!wxApi.isWXAppInstalled) {
CenterToast.show("您没有安装微信客户端,请先下载安装")
return
}
if (isLaunchingWechat) return
isLaunchingWechat = true
isLoginWxAuthor = true
val req = SendAuth.Req()
req.scope = "snsapi_userinfo" // 只能填 snsapi_userinfo
req.state = context.packageName + Math.random() * 1000 + "_phone"
wxApi.sendReq(req)
val state = context.packageName + java.util.UUID.randomUUID().toString()
viewModelScope.launch {
try {
WechatRequests.authorize(wxApi, state)?.let { message ->
isLoginWxAuthor = false
CenterToast.show(message)
}
} finally {
isLaunchingWechat = false
}
}
}else{
CenterToast.show("请先同意用户协议和隐私政策")
}

View File

@ -1,30 +1,43 @@
package com.img.rabbit.viewmodel
import com.img.rabbit.bean.response.ServiceWxLinkEntity
import android.util.Log
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.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat
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() {
private val TAG = "MineViewModel"
private var isOpeningService = false
//请求客服连接
fun requestServiceLink(api: IWXAPI){
mLaunch {
val response = ApiManager.serviceVo.wxService()
if (response.status) {
contactClientService(response.data, api)
if (isOpeningService) return
isOpeningService = true
viewModelScope.launch {
try {
val message = withContext(Dispatchers.IO) {
if (!api.isWXAppInstalled) return@withContext "未安装微信客户端"
val response = ApiManager.serviceVo.wxService()
if (!response.status) {
return@withContext "暂时无法获取客服信息,请稍后重试"
}
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)
}
}
}
}

View File

@ -1,41 +1,57 @@
@file:OptIn(DelicateCoroutinesApi::class)
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.WXAuthEvent
import com.img.rabbit.utils.wechatAuthResult
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.umeng.socialize.weixin.view.WXCallbackActivity
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class WXEntryActivity : WXCallbackActivity() {
override fun onResp(resp: BaseResp?) {
if (resp?.type == ConstantsAPI.COMMAND_SENDAUTH) {
when (resp.errCode) {
BaseResp.ErrCode.ERR_OK -> {
val authResp = resp as SendAuth.Resp
//val wxState = WxBean(code = authResp.code,state = authResp.state)
GlobalScope.launch {
//GlobalStateManager(this@WXEntryActivity).storeGlobalWxAuthorization(authResp.code)
AppEventBus.post(
WXAuthEvent.AuthResult(
code = authResp.code,
authType = 0
)
)
finish()
}
}
else -> {}
}
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?) {
try {
if (resp?.type == ConstantsAPI.COMMAND_SENDAUTH) {
val event = wechatAuthResult(resp.errCode, (resp as? SendAuth.Resp)?.code)
if (!AppEventBus.tryPost(event)) {
Log.w("WXEntryActivity", "微信授权结果未能投递")
}
} else {
super.onResp(resp)
}
} catch (e: Exception) {
Log.e("WXEntryActivity", "微信授权回调异常", e)
AppEventBus.tryPost(WXAuthEvent.AuthFailure("微信授权失败,请重试"))
} finally {
finish()
}
}
}