From b1f3e10453343a4f9bf9756f7bf4ee9b63790406 Mon Sep 17 00:00:00 2001 From: kunfei Date: Sat, 23 Apr 2022 23:17:48 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../io/legado/app/utils/RegexExtensions.kt | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/io/legado/app/utils/RegexExtensions.kt b/app/src/main/java/io/legado/app/utils/RegexExtensions.kt index 5d0b665b7..5f0fe41a6 100644 --- a/app/src/main/java/io/legado/app/utils/RegexExtensions.kt +++ b/app/src/main/java/io/legado/app/utils/RegexExtensions.kt @@ -2,32 +2,39 @@ package io.legado.app.utils import io.legado.app.exception.RegexTimeoutException import io.legado.app.help.CrashHandler +import kotlinx.coroutines.DelicateCoroutinesApi +import kotlinx.coroutines.Dispatchers.IO +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import splitties.init.appCtx -import kotlin.concurrent.thread import kotlin.coroutines.resume +/** + * 带有超时检测的正则替换 + * 超时重启apk,线程不能强制结束,只能重启apk + */ +@DelicateCoroutinesApi suspend fun CharSequence.replace(regex: Regex, replacement: String, timeout: Long): String { + val charSequence = this return suspendCancellableCoroutine { block -> - val thread = thread { + val scope = GlobalScope.launch(IO) { try { - val result = regex.replace(this, replacement) + val result = regex.replace(charSequence, replacement) block.resume(result) } catch (e: Exception) { block.cancel(e) } } mainHandler.postDelayed({ - if (thread.isAlive) { + if (scope.isActive) { val timeoutMsg = "替换超时,将在3秒后重启应用\n替换规则$regex\n替换内容:${this}" val exception = RegexTimeoutException(timeoutMsg) block.cancel(exception) appCtx.longToastOnUi(timeoutMsg) CrashHandler.saveCrashInfo2File(exception) mainHandler.postDelayed({ - if (thread.isAlive) { - appCtx.restart() - } + appCtx.restart() }, 3000) } }, timeout)