refactor(base): 优化协程作用域和空安全处理
- 将自定义CoroutineScope替换为lifecycleScope以避免内存泄漏 - 添加runCatching包装器处理潜在异常并记录错误日志 - 使用安全调用操作符替代强制调用防止空指针异常 - 在CountDownTimer中正确管理生命周期以避免内存泄漏 - 修复设备信息获取中的数组越界风险 - 统一异步操作的线程切换方式 - 保护Fragment中的_binding访问权限 - 改进相机助手对象引用的安全性检查
This commit is contained in:
@@ -30,10 +30,10 @@ import com.sw.platecabinet.utils.IntervalExecutor
|
||||
import com.sw.platecabinet.utils.SpTool
|
||||
import com.sw.platecabinet.view.CustomLoadingDialog
|
||||
import com.sw.platecabinet.viewmodel.UserViewModel
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import timber.log.Timber
|
||||
|
||||
/**
|
||||
@@ -142,8 +142,7 @@ abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {
|
||||
onRightDoubleClick()
|
||||
}
|
||||
)
|
||||
val scope = CoroutineScope(Dispatchers.Main)
|
||||
timeJob = scope.launch {
|
||||
timeJob = lifecycleScope.launch {
|
||||
DateTimeUtils.realTimeChineseDateFlow()
|
||||
.collect { date ->
|
||||
it.tvRightTime.text = date
|
||||
@@ -347,7 +346,9 @@ abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {
|
||||
val alreadyExists = featureMatches.any { it }
|
||||
if (!alreadyExists) {
|
||||
//当前特征不存在,保存
|
||||
faceList.add(getNewFaceEntity(model))
|
||||
runCatching { getNewFaceEntity(model) }
|
||||
.onSuccess { faceList.add(it) }
|
||||
.onFailure { Timber.e(it, "人脸特征解码失败: userId=${model.userId}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -378,13 +379,13 @@ abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {
|
||||
}
|
||||
|
||||
fun clearAllFace(block: () -> Unit) {
|
||||
Thread {
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
val faceDao = FaceDatabase.getInstance(App.getContext()).faceDao()
|
||||
faceDao.deleteAll()
|
||||
faceDao.resetId()
|
||||
recognizeViewModel.refreshFaceList()
|
||||
runOnUiThread { block() }
|
||||
}.start()
|
||||
withContext(Dispatchers.Main) { block() }
|
||||
}
|
||||
}
|
||||
|
||||
private var permissionCallback: ((isGranted: Boolean) -> Unit)? = null
|
||||
|
||||
Reference in New Issue
Block a user