核心重构 — 去除 channel 字段,引入 sourceAccount 模型: - 从 ImportedEvent、Rule、EnhancedRule、OcrRule 等接口中彻底移除 channel 字段 - rules.ts 中 resolveChannelAccount → resolveSourceAccount,规则匹配与账户解析不再依赖渠道概念 - dedup.ts 重写去重逻辑:从基于渠道匹配改为基于交易对手(counterparty)匹配,支持相同金额/交易对手/时间窗口的多级置信度判断 - transferRecognizer.ts 增加资产负债表账户校验,确保转账双方均为 Assets/Liabilities 类账户 - 全局替换影响:types、rules、ocr、adapters、adapters-migrations、所有服务层和测试 新增基础设施: - domain/constants.ts — 统一常量定义(支付包名、截图关键词、去重参数、方向检测函数 detectDirection()),消除 OCR/SMS/截图等模块的重复定义 - domain/channelConfig.ts — 渠道配置系统(支付宝/微信/银行),支持按包名和名称查找 - domain/pipelineSingleton.ts — 共享 BillPipeline 单例,解决 importStore/automationStore 的互斥锁共享问题 - domain/transactionBuilder.ts — 统一交易构建入口 buildAndSaveTransaction(),同时服务手动录入和无障碍监听 OCR 增强: - 新增账单详情页解析(parseDetailPageBill),支持支付宝/微信详情页结构化提取 - checkIsDetailPage() 识别详情页特征词,防止误提取(如"消费1次"被误读为金额) - 金额正则支持千分位逗号分隔,商户名正则改用 lookahead 边界匹配 - 时间解析支持中文格式(年月日)和跨年推断 - OcrProcessor 新增详情页路由,跳过 Layer 1 规则匹配 UI 全面升级: - 主题重设计:accent 色从绿色改为靛蓝(#4F46E5),深色模式适配 OLED 纯黑,引入 Quicksand/Caveat 字体 - 新增 commonStyles.ts 统一 chip/input/modal 等通用样式 - 首页 Bento 网格布局:净资产英雄卡片 + 定期账单/月度统计并排展示 - 报表新增周报标签页,月报整合日历视图(支持点击查看当日交易明细) - TrendLine 图表从 View 条形图重写为 SVG 贝塞尔曲线 - CategoryPicker 从水平滚动改为 4 列网格 + emoji 图标 - Button/Card 增加 press 缩放动画 管道与自动化改进: - automationPipeline.ts 新增 handleIncomingBillEvent() 实时账单处理(悬浮账单卡片 + 前台 Alert 确认) - 新增无障碍文本直解析 parseAndProcessAccessibilityTexts(),微信/支付宝详情页绕过 OCR - rules.ts 新增智能还款检测(花呗/信用卡还款自动路由)和退款视为收入处理 - metadataStore 默认规则精简为 6 条通用规则,移除约 20 条个人化硬编码规则 存储与同步: - storePersistence.ts 原子写入 + 崩溃恢复 + 重试机制 - 备份升级到 v2 格式,包含 settings 和 metadata - 同步路径统一从 mobile.bean 改为 main.bean - _layout.tsx 启动时自动迁移旧 mobile.bean 到 main.bean 其他: - 删除独立日历页面,功能合并到报表月报标签 - i18n 清理:移除渠道相关翻译,新增 50+ 翻译键 - docs/android-build-guide.md 重写为 APK 体积优化指南 - 新增 design-system/beancount-mobile/MASTER.md 设计系统文档 - 测试全面更新覆盖以上所有变更
579 lines
23 KiB
Kotlin
579 lines
23 KiB
Kotlin
package com.beancount.mobile.accessibility
|
||
|
||
import android.accessibilityservice.AccessibilityService
|
||
import android.accessibilityservice.AccessibilityServiceInfo
|
||
import android.content.Context
|
||
import android.graphics.Bitmap
|
||
import android.hardware.display.DisplayManager
|
||
import android.os.Build
|
||
import android.os.Handler
|
||
import android.os.Looper
|
||
import android.util.Log
|
||
import android.view.Display
|
||
import android.view.Surface
|
||
import android.view.accessibility.AccessibilityEvent
|
||
import com.facebook.react.modules.core.DeviceEventManagerModule
|
||
import com.facebook.react.bridge.ReactApplicationContext
|
||
import com.facebook.react.bridge.WritableNativeMap
|
||
import com.facebook.react.bridge.WritableNativeArray
|
||
import java.io.ByteArrayOutputStream
|
||
import android.util.Base64
|
||
import android.view.accessibility.AccessibilityNodeInfo
|
||
|
||
/**
|
||
* 无障碍账单识别服务(plan.md「3.6 无障碍服务」+「决策 4 Config Plugin」)。
|
||
*
|
||
* 参考 AutoAccounting 的 SelectToSpeakService:
|
||
* - 监听支付 App 的页面切换(TYPE_WINDOW_STATE_CHANGED)
|
||
* - 页面签名匹配时自动截图 → OCR → 推送到 JS 层
|
||
* - 横屏免打扰(游戏/视频时不触发)
|
||
* - ocrDoing 守卫(防止重复触发)
|
||
*
|
||
* 伪装说明:plan.md 决策 3「纯开源侧载」保留无障碍伪装(非应用商店分发)。
|
||
* 注意:本服务类名在 manifest 中声明为 BillingAccessibilityService,
|
||
* 伪装为系统服务(包名 com.beancount.mobile.accessibility)仅在侧载版本保留。
|
||
*
|
||
* 通过 DeviceEventEmitter 把识别事件推送到 JS 层 automationStore。
|
||
*
|
||
* ⚠️ 与 src/domain/constants.ts 同步:PAYMENT_PACKAGES
|
||
* 修改时需两边同时更新。
|
||
*/
|
||
class BillingAccessibilityService : AccessibilityService() {
|
||
|
||
companion object {
|
||
private const val TAG = "BillingAccessibility"
|
||
private const val PREFS_NAME = "billing_accessibility_prefs"
|
||
private const val PREF_PAGE_SIGNATURES = "page_signatures"
|
||
|
||
@Volatile
|
||
var instance: BillingAccessibilityService? = null
|
||
private set
|
||
|
||
/** 支付 App 白名单。 */
|
||
val PAYMENT_PACKAGES = setOf(
|
||
"com.eg.android.AlipayGphone", // 支付宝
|
||
"com.tencent.mm", // 微信
|
||
"com.unionpay", // 银联
|
||
"com.cmbchina", // 招商银行
|
||
"com.icbc", // 工商银行
|
||
"com.chinamworld.main", // 中国银行
|
||
"com.ccbrcb", // 建设银行
|
||
"com.bankcomm.Bankcomm", // 交通银行
|
||
"com.tencent.mobileqq", // 手机QQ
|
||
"com.tencent.tim" // TIM
|
||
)
|
||
|
||
/** 厂商桌面包名(过滤,不触发 OCR)。 */
|
||
private val LAUNCHER_PACKAGES = setOf(
|
||
"com.google.android.apps.nexuslauncher",
|
||
"com.sec.android.app.launcher",
|
||
"com.miui.home",
|
||
"com.huawei.android.launcher",
|
||
"com.oppo.launcher",
|
||
"com.bbk.launcher2",
|
||
"com.android.launcher3",
|
||
)
|
||
|
||
/** OCR 触发防抖:500ms 内的内容变化合并为一次。 */
|
||
private const val CONTENT_CHANGE_DEBOUNCE_MS = 500L
|
||
}
|
||
|
||
private var ocrDoing = false
|
||
private val handler = Handler(Looper.getMainLooper())
|
||
private val debounceRunnable = Runnable { processContentChange() }
|
||
@Volatile private var topPackage: String? = null
|
||
@Volatile private var topActivity: String? = null
|
||
/** 已记住的页面签名(pkg|activity),匹配时自动触发 OCR。持久化到 SharedPreferences。 */
|
||
private val pageSignatures = java.util.concurrent.CopyOnWriteArraySet<String>()
|
||
private var floatingHelper: FloatingHelper? = null
|
||
|
||
override fun onServiceConnected() {
|
||
super.onServiceConnected()
|
||
instance = this
|
||
Log.i(TAG, "无障碍账单识别服务已连接")
|
||
loadPageSignatures()
|
||
configureService()
|
||
}
|
||
|
||
/** 动态配置服务能力(截图 + 页面变化监听)。 */
|
||
private fun configureService() {
|
||
val info = AccessibilityServiceInfo().apply {
|
||
eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED or
|
||
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
|
||
feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
|
||
flags = AccessibilityServiceInfo.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY or
|
||
AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS or
|
||
AccessibilityServiceInfo.DEFAULT
|
||
notificationTimeout = 100L
|
||
}
|
||
serviceInfo = info
|
||
}
|
||
|
||
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
|
||
if (ocrDoing) return // 处理中,跳过
|
||
val eventPackage = event?.packageName?.toString() ?: return
|
||
|
||
when (event.eventType) {
|
||
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
|
||
val activityName = event.className?.toString() ?: ""
|
||
if (filterPackage(eventPackage, activityName)) return
|
||
topPackage = eventPackage
|
||
topActivity = activityName
|
||
Log.d(TAG, "页面切换: $eventPackage / $activityName")
|
||
|
||
// 更新悬浮窗助手状态
|
||
updateFloatingHelperVisibility(eventPackage)
|
||
|
||
if (PAYMENT_PACKAGES.contains(eventPackage)) {
|
||
scheduleContentChange()
|
||
}
|
||
|
||
// 调试:如果是微信或支付宝,延迟 800ms 抓取并打印全屏无障碍文本内容
|
||
if (eventPackage == "com.tencent.mm" || eventPackage == "com.eg.android.AlipayGphone") {
|
||
handler.postDelayed({
|
||
val rootNode = rootInActiveWindow
|
||
val texts = mutableListOf<String>()
|
||
dumpNodeTexts(rootNode, texts)
|
||
rootNode?.recycle()
|
||
|
||
val reactContext = ReactContextHolder.context
|
||
if (reactContext != null) {
|
||
try {
|
||
val map = WritableNativeMap().apply {
|
||
putString("package", eventPackage)
|
||
putString("activity", activityName)
|
||
val array = WritableNativeArray()
|
||
for (t in texts) {
|
||
array.pushString(t)
|
||
}
|
||
putArray("texts", array)
|
||
}
|
||
reactContext
|
||
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
|
||
.emit("billingDebugNodes", map)
|
||
} catch (e: Exception) {
|
||
// 忽略
|
||
}
|
||
}
|
||
}, 800)
|
||
}
|
||
}
|
||
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> {
|
||
if (PAYMENT_PACKAGES.contains(eventPackage)) {
|
||
scheduleContentChange()
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
private fun updateFloatingHelperVisibility(pkg: String?) {
|
||
handler.post {
|
||
if (pkg != null && PAYMENT_PACKAGES.contains(pkg)) {
|
||
if (floatingHelper == null) {
|
||
floatingHelper = FloatingHelper(this)
|
||
floatingHelper?.show()
|
||
}
|
||
} else {
|
||
floatingHelper?.dismiss()
|
||
floatingHelper = null
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 防抖:500ms 内的多次内容变化合并。 */
|
||
private fun scheduleContentChange() {
|
||
handler.removeCallbacks(debounceRunnable)
|
||
handler.postDelayed(debounceRunnable, CONTENT_CHANGE_DEBOUNCE_MS)
|
||
}
|
||
|
||
/** 内容变化处理:检查页面签名 → 提取文本 → 发送给 JS(JS 控制是否 OCR 兜底)。 */
|
||
private fun processContentChange() {
|
||
if (ocrDoing) return
|
||
val pkg = topPackage ?: return
|
||
|
||
// 横屏免打扰(plan.md「3.10」)
|
||
if (isLandscape()) {
|
||
Log.d(TAG, "横屏免打扰,跳过")
|
||
return
|
||
}
|
||
|
||
// 页面签名匹配(若已记住页面则触发)
|
||
val activity = topActivity ?: ""
|
||
val sigKey = "$pkg|$activity"
|
||
if (!pageSignatures.contains(sigKey)) {
|
||
return // 未记住的页面不自动触发
|
||
}
|
||
|
||
// 抓取并提取屏幕所有无障碍文本,并推送至 JS 侧进行解析/控制
|
||
val rootNode = rootInActiveWindow
|
||
val texts = mutableListOf<String>()
|
||
dumpNodeTexts(rootNode, texts)
|
||
rootNode?.recycle()
|
||
|
||
val reactContext = ReactContextHolder.context
|
||
if (reactContext != null) {
|
||
try {
|
||
val map = WritableNativeMap().apply {
|
||
putString("package", pkg)
|
||
putString("activity", activity)
|
||
putString("signature", sigKey)
|
||
val array = WritableNativeArray()
|
||
for (t in texts) {
|
||
array.pushString(t)
|
||
}
|
||
putArray("texts", array)
|
||
}
|
||
reactContext
|
||
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
|
||
.emit("billingDebugNodes", map)
|
||
} catch (e: Exception) {
|
||
Log.e(TAG, "推送内容变化节点文本失败: ${e.message}")
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 截图并触发 OCR 处理(Android 11+)。 */
|
||
private fun takeScreenshotAndProcess(packageName: String) {
|
||
if (ocrDoing) return
|
||
ocrDoing = true
|
||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||
ocrDoing = false
|
||
return
|
||
}
|
||
try {
|
||
takeScreenshot(
|
||
Display.DEFAULT_DISPLAY,
|
||
mainExecutor,
|
||
object : TakeScreenshotCallback {
|
||
override fun onSuccess(result: ScreenshotResult) {
|
||
try {
|
||
val bitmap = Bitmap.wrapHardwareBuffer(result.hardwareBuffer, result.colorSpace)
|
||
result.hardwareBuffer.close()
|
||
if (bitmap != null) {
|
||
val base64 = bitmapToBase64(bitmap)
|
||
bitmap.recycle()
|
||
// 推送到 JS 层(NativeEventEmitter)
|
||
sendScreenshotEvent(base64, packageName)
|
||
}
|
||
} finally {
|
||
ocrDoing = false
|
||
}
|
||
}
|
||
override fun onFailure(errorCode: Int) {
|
||
Log.e(TAG, "截图失败: errorCode=$errorCode")
|
||
ocrDoing = false
|
||
}
|
||
}
|
||
)
|
||
} catch (e: Throwable) {
|
||
Log.e(TAG, "调用 takeScreenshot 失败: ${e.message}", e)
|
||
ocrDoing = false
|
||
}
|
||
}
|
||
|
||
/** 把截图以 base64 推送到 JS 层(由 JS 端 OcrProcessor 处理)。 */
|
||
private fun sendScreenshotEvent(base64: String, packageName: String) {
|
||
val reactContext = ReactContextHolder.context ?: return
|
||
try {
|
||
reactContext
|
||
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
|
||
.emit("billingScreenshot", writableMapOf(
|
||
"base64" to base64,
|
||
"packageName" to packageName,
|
||
"timestamp" to System.currentTimeMillis()
|
||
))
|
||
} catch (e: Exception) {
|
||
Log.e(TAG, "推送截图事件失败: ${e.message}")
|
||
}
|
||
}
|
||
|
||
/** 手动触发一次 OCR(临时隐藏悬浮窗避开遮挡,并在 150ms 后触发截图)。 */
|
||
fun triggerManualOcr() {
|
||
val pkg = topPackage ?: return
|
||
handler.post {
|
||
floatingHelper?.collapse()
|
||
floatingHelper?.hideTemporarily()
|
||
}
|
||
|
||
// 150ms 后触发截图(此时悬浮窗已瞬间隐藏,避免遮挡和误匹配)
|
||
handler.postDelayed({
|
||
try {
|
||
takeScreenshotAndProcess(pkg)
|
||
} catch (e: Exception) {
|
||
Log.e(TAG, "手动触发 OCR 失败: ${e.message}")
|
||
} finally {
|
||
// 截图完成,瞬间恢复显示悬浮球
|
||
handler.post {
|
||
floatingHelper?.showTemporarily()
|
||
}
|
||
}
|
||
}, 150)
|
||
}
|
||
|
||
/** 手动触发一次节点文本提取并发送到 JS,从而让 JS 优先尝试直接文本解析。 */
|
||
fun triggerManualExtraction() {
|
||
handler.post {
|
||
floatingHelper?.collapse()
|
||
}
|
||
val pkg = topPackage ?: return
|
||
val activity = topActivity ?: ""
|
||
val sigKey = "$pkg|$activity"
|
||
|
||
val rootNode = rootInActiveWindow
|
||
val texts = mutableListOf<String>()
|
||
dumpNodeTexts(rootNode, texts)
|
||
rootNode?.recycle()
|
||
|
||
val reactContext = ReactContextHolder.context
|
||
if (reactContext != null) {
|
||
try {
|
||
val map = WritableNativeMap().apply {
|
||
putString("package", pkg)
|
||
putString("activity", activity)
|
||
putString("signature", sigKey)
|
||
putBoolean("isManual", true)
|
||
val array = WritableNativeArray()
|
||
for (t in texts) {
|
||
array.pushString(t)
|
||
}
|
||
putArray("texts", array)
|
||
}
|
||
reactContext
|
||
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
|
||
.emit("billingDebugNodes", map)
|
||
} catch (e: Exception) {
|
||
Log.e(TAG, "手动触发节点文本提取失败: ${e.message}")
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 记住当前页面(用户主动标记应触发 OCR 的页面)。持久化到 SharedPreferences。 */
|
||
fun rememberCurrentPage() {
|
||
val pkg = topPackage ?: return
|
||
val activity = topActivity ?: ""
|
||
val sig = "$pkg|$activity"
|
||
if (pageSignatures.add(sig)) {
|
||
savePageSignatures()
|
||
Log.i(TAG, "已记住页面: $sig")
|
||
handler.post {
|
||
android.widget.Toast.makeText(this, "已记住页面签名:\n$sig", android.widget.Toast.LENGTH_LONG).show()
|
||
}
|
||
|
||
// 抓取并提取屏幕所有无障碍文本
|
||
val texts = mutableListOf<String>()
|
||
val rootNode = rootInActiveWindow
|
||
dumpNodeTexts(rootNode, texts)
|
||
rootNode?.recycle()
|
||
|
||
// 推送事件到 JS 端,使 npx expo start 终端控制台可以接收并打印日志
|
||
val reactContext = ReactContextHolder.context
|
||
if (reactContext != null) {
|
||
try {
|
||
val map = WritableNativeMap().apply {
|
||
putString("package", pkg)
|
||
putString("activity", activity)
|
||
putString("signature", sig)
|
||
val array = WritableNativeArray()
|
||
for (t in texts) {
|
||
array.pushString(t)
|
||
}
|
||
putArray("texts", array)
|
||
}
|
||
reactContext
|
||
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
|
||
.emit("billingPageRemembered", map)
|
||
} catch (e: Exception) {
|
||
Log.e(TAG, "推送记住页面事件失败: ${e.message}")
|
||
}
|
||
}
|
||
} else {
|
||
handler.post {
|
||
android.widget.Toast.makeText(this, "该页面签名已存在:\n$sig", android.widget.Toast.LENGTH_LONG).show()
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 获取已记住的页面签名列表(供 JS 端展示)。 */
|
||
fun getPageSignatures(): Set<String> {
|
||
return pageSignatures.toSet()
|
||
}
|
||
|
||
/** 清空所有已记住的页面签名。 */
|
||
fun clearPageSignatures() {
|
||
pageSignatures.clear()
|
||
try {
|
||
val prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||
prefs.edit().remove(PREF_PAGE_SIGNATURES).apply()
|
||
Log.i(TAG, "已清空全部记住的页面并从 SharedPreferences 中移除键值")
|
||
} catch (e: Exception) {
|
||
Log.e(TAG, "清空 SharedPreferences 失败: ${e.message}")
|
||
}
|
||
}
|
||
|
||
/** 删除指定页面签名。 */
|
||
fun removePageSignature(sig: String) {
|
||
if (pageSignatures.remove(sig)) {
|
||
savePageSignatures()
|
||
Log.i(TAG, "已删除页面签名: $sig")
|
||
}
|
||
}
|
||
|
||
/** 获取当前顶部包名(供 JS 判断当前页面)。 */
|
||
fun getTopPackage(): String? = topPackage
|
||
|
||
/** 获取当前顶部 Activity。 */
|
||
fun getTopActivity(): String? = topActivity
|
||
|
||
/** 从 SharedPreferences 加载已记住的页面签名。 */
|
||
private fun loadPageSignatures() {
|
||
try {
|
||
val prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||
val saved = prefs.getStringSet(PREF_PAGE_SIGNATURES, emptySet()) ?: emptySet()
|
||
pageSignatures.clear()
|
||
pageSignatures.addAll(saved)
|
||
Log.i(TAG, "已加载 ${pageSignatures.size} 个记住的页面签名")
|
||
} catch (e: Exception) {
|
||
Log.e(TAG, "加载页面签名失败: ${e.message}")
|
||
}
|
||
}
|
||
|
||
/** 保存页面签名到 SharedPreferences。 */
|
||
private fun savePageSignatures() {
|
||
try {
|
||
val prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||
if (pageSignatures.isEmpty()) {
|
||
prefs.edit().remove(PREF_PAGE_SIGNATURES).apply()
|
||
} else {
|
||
prefs.edit().putStringSet(PREF_PAGE_SIGNATURES, HashSet(pageSignatures)).apply()
|
||
}
|
||
} catch (e: Exception) {
|
||
Log.e(TAG, "保存页面签名失败: ${e.message}")
|
||
}
|
||
}
|
||
|
||
/** 横屏检测(plan.md「3.10 横屏免打扰」)。 */
|
||
private fun isLandscape(): Boolean {
|
||
val dm = getSystemService(DisplayManager::class.java)?.getDisplay(Display.DEFAULT_DISPLAY)
|
||
?: return false
|
||
val rotation = dm.rotation
|
||
return rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270
|
||
}
|
||
|
||
/** 过滤系统组件/桌面(不触发 OCR)。 */
|
||
private fun filterPackage(pkg: String, className: String): Boolean {
|
||
val p = pkg.lowercase()
|
||
// 针对自身应用的特殊过滤:只允许 MainActivity 通过以触发隐藏悬浮窗;
|
||
// 其他自身组件(如悬浮球容器 LinearLayout)一律过滤,避免自毁式关闭。
|
||
if (pkg == packageName) {
|
||
return className != "com.example.beanmobile.MainActivity"
|
||
}
|
||
if (p == "android" || p.startsWith("com.android.") || p.startsWith("com.google.android.")) return true
|
||
if (p.contains("systemui") || p.contains("settings") || p.contains("inputmethod") || p.contains("keyboard") || p.contains("input")) return true
|
||
if (LAUNCHER_PACKAGES.any { p.contains(it) }) return true
|
||
return false
|
||
}
|
||
|
||
/** Bitmap → base64(JPEG 质量 60,参考 AutoAccounting bitmapToBase64)。 */
|
||
private fun bitmapToBase64(bitmap: Bitmap): String {
|
||
// 安全起见,如果 bitmap 是 HARDWARE 格式,将其复制为 ARGB_8888 软件格式
|
||
val softwareBitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && bitmap.config == Bitmap.Config.HARDWARE) {
|
||
bitmap.copy(Bitmap.Config.ARGB_8888, false)
|
||
} else {
|
||
bitmap
|
||
}
|
||
val baos = ByteArrayOutputStream()
|
||
softwareBitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos)
|
||
if (softwareBitmap !== bitmap) {
|
||
softwareBitmap.recycle()
|
||
}
|
||
return "data:image/jpeg;base64," + Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP)
|
||
}
|
||
|
||
/** 辅助:构造 WritableNativeMap。 */
|
||
private fun writableMapOf(vararg pairs: Pair<String, Any?>): WritableNativeMap {
|
||
val map = WritableNativeMap()
|
||
for ((k, v) in pairs) {
|
||
when (v) {
|
||
is String -> map.putString(k, v)
|
||
is Int -> map.putInt(k, v)
|
||
is Long -> map.putDouble(k, v.toDouble())
|
||
is Boolean -> map.putBoolean(k, v)
|
||
is Number -> map.putDouble(k, v.toDouble())
|
||
is WritableNativeMap -> map.putMap(k, v)
|
||
is WritableNativeArray -> map.putArray(k, v)
|
||
else -> map.putNull(k)
|
||
}
|
||
}
|
||
return map
|
||
}
|
||
|
||
/** 将当前应用拉到前台以显示确认弹窗 */
|
||
fun bringAppToForeground() {
|
||
try {
|
||
val intent = packageManager.getLaunchIntentForPackage(packageName)
|
||
if (intent != null) {
|
||
intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
|
||
startActivity(intent)
|
||
Log.i(TAG, "已成功拉起本应用到前台显示弹窗")
|
||
}
|
||
} catch (e: Exception) {
|
||
Log.e(TAG, "拉起应用到前台失败: ${e.message}")
|
||
}
|
||
}
|
||
|
||
/** 递归提取无障碍节点树的全部文本。 */
|
||
private fun dumpNodeTexts(node: AccessibilityNodeInfo?, list: MutableList<String>) {
|
||
if (node == null) return
|
||
val text = node.text?.toString()
|
||
if (!text.isNullOrBlank()) {
|
||
list.add(text)
|
||
}
|
||
val childCount = node.childCount
|
||
for (i in 0 until childCount) {
|
||
val child = node.getChild(i) ?: continue
|
||
dumpNodeTexts(child, list)
|
||
child.recycle()
|
||
}
|
||
}
|
||
|
||
/** 递归遍历无障碍节点树,检查是否包含指定的任意一个关键字。 */
|
||
private fun findTextInNode(node: AccessibilityNodeInfo?, keywords: List<String>): Boolean {
|
||
if (node == null) return false
|
||
val text = node.text?.toString()
|
||
if (text != null) {
|
||
for (keyword in keywords) {
|
||
if (text.contains(keyword)) {
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
val childCount = node.childCount
|
||
for (i in 0 until childCount) {
|
||
val child = node.getChild(i) ?: continue
|
||
val found = findTextInNode(child, keywords)
|
||
child.recycle()
|
||
if (found) return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
override fun onInterrupt() {
|
||
Log.w(TAG, "无障碍服务被中断")
|
||
}
|
||
|
||
override fun onUnbind(intent: android.content.Intent?): Boolean {
|
||
floatingHelper?.dismiss()
|
||
floatingHelper = null
|
||
instance = null
|
||
return super.onUnbind(intent)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* RN 上下文持有者(由 MainApplication 注入)。
|
||
* 无障碍服务运行在系统进程,需通过静态引用访问 RN 上下文以发送事件。
|
||
*/
|
||
object ReactContextHolder {
|
||
@Volatile var context: ReactApplicationContext? = null
|
||
}
|