Skip to content

Commit 058fa6d

Browse files
ShuttleLabclaude
andcommitted
Make the poll loop crash-proof + log heartbeat
Likely root cause of "not executing": a single uncaught exception in the heartbeat coroutine (scan or notify) would terminate the whole launch coroutine, permanently stopping the 5s poll — so only "服务启动" appeared and never a poll line. Now each iteration wraps scan and notify in try/catch (a transient error can no longer kill polling), logs "心跳循环已启动" on start, and logs any scan/notify exception with the iteration number — so the activity log distinguishes loop-not- running vs scan-hanging vs scan-throwing. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 0a8d14e commit 058fa6d

1 file changed

Lines changed: 16 additions & 3 deletions

File tree

‎app/src/main/java/com/smsforwarder/ForwardService.kt‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,12 +114,25 @@ class ForwardService : Service() {
114114
private fun startHeartbeat() {
115115
loop?.cancel()
116116
loop = scope.launch {
117+
DebugLog.log(applicationContext, "心跳循环已启动")
118+
var n = 0
117119
while (isActive) {
118-
withContext(Dispatchers.IO) { SmsScanner.scan(applicationContext) }
119-
val mgr = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
120-
mgr.notify(NOTIF_ID, buildNotification())
120+
n++
121+
// 每一步都兜住异常:任何单次错误都不能杀死整个轮询循环
122+
try {
123+
withContext(Dispatchers.IO) { SmsScanner.scan(applicationContext) }
124+
} catch (e: Exception) {
125+
DebugLog.log(applicationContext, "心跳#$n 轮询异常:${e.message}")
126+
}
127+
try {
128+
val mgr = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
129+
mgr.notify(NOTIF_ID, buildNotification())
130+
} catch (e: Exception) {
131+
DebugLog.log(applicationContext, "心跳#$n 通知异常:${e.message}")
132+
}
121133
delay(Prefs.pollSeconds(applicationContext) * 1000L)
122134
}
135+
DebugLog.log(applicationContext, "心跳循环结束(isActive=false)")
123136
}
124137
}
125138

0 commit comments

Comments
 (0)