From 6b367573371423215f0de92507a7aab1478118c2 Mon Sep 17 00:00:00 2001 From: lunaticbum Date: Mon, 16 Nov 2026 11:38:58 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20Task=2012=20=EC=99=84=EB=A3=8C=20-=20For?= =?UTF-8?q?eGroundService=20targetUrls=20=EB=8F=99=EA=B8=B0=ED=99=94=20?= =?UTF-8?q?=EB=B0=8F=20YoutubeDL=20Mutex=20=EC=A7=81=EB=A0=AC=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ForeGroundService.kt: * addToTargetYtubeUrl(): targetUrls 접근을 synchronized(targetUrls) 블록으로 보호 * downloadVideo(): 비관리 CoroutineScope 대신 serviceScope.launch(Dispatchers.IO) 사용 및 downloadMutex.withLock 적용으로 YoutubeDL 동시 실행 경쟁 방지 * currentProcessId, lastProGress에 @Volatile 적용 및 finally 블록에서 대기열 후속 작업 안전 트리거 * launchAppleMusic(): CoroutineScope(Dispatchers.Main) -> serviceScope.launch(Dispatchers.Main) 전환 - TODO.md: 2-3 항목 완료 처리 - 검증: ./gradlew :app:compileDebugKotlin 빌드 성공 확인 (3s) --- TODO.md | 2 +- .../launcher/helpers/ForeGroundService.kt | 32 +++++++++++-------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/TODO.md b/TODO.md index a70cce6c..2b23b03a 100644 --- a/TODO.md +++ b/TODO.md @@ -80,7 +80,7 @@ - `app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt:68, 106` — `pushLocation()` 호출마다 `Executors.newSingleThreadScheduledExecutor().schedule(...)`로 새 스레드 풀을 생성하고 `shutdown()`을 호출하지 않음. 또한 `130-131`행에서 `Companion.lastWeather.clear()` / `addAll()`을 백그라운드 스레드에서 동기화 없이 수정함. - **작업**: 단일 공유 `CoroutineScope` + `delay(5000)`으로 대체하고 `lastWeather` 갱신 시 스레드 안전한 컬렉션 또는 `StateFlow` 사용. -- [ ] **2-3. `ForeGroundService` 공유 상태 및 `YoutubeDL` 동시 실행 제어** +- [x] **2-3. `ForeGroundService` 공유 상태 및 `YoutubeDL` 동시 실행 제어** - `app/src/main/kotlin/bums/lunatic/launcher/helpers/ForeGroundService.kt:426, 542-598` — `companion object`의 `targetUrls`(일반 `ArrayList`)와 `lastProGress`, `currentProcessId`가 여러 `CoroutineScope(Dispatchers.IO)`에서 동기화 없이 접근/수정됨. - **작업**: `Channel` 또는 `Mutex` 기반 순차 다운로드 큐로 전환하고, `targetUrls`를 스레드 안전 구조로 교체. diff --git a/app/src/main/kotlin/bums/lunatic/launcher/helpers/ForeGroundService.kt b/app/src/main/kotlin/bums/lunatic/launcher/helpers/ForeGroundService.kt index 6efe36ae..08fe86f6 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/helpers/ForeGroundService.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/helpers/ForeGroundService.kt @@ -39,6 +39,8 @@ import io.realm.kotlin.internal.interop.sync.CancellableTimer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import okhttp3.ConnectionPool import okhttp3.OkHttpClient import okhttp3.Request @@ -517,20 +519,19 @@ class ForeGroundService : Service() { fun addToTargetYtubeUrl(url : String? = null, forMusic: Boolean = false) { Blog.LOGE("url $url") - url?.let { url -> - if (url.length > 0) { - targetUrls.add(url to forMusic) + val nextTask = synchronized(targetUrls) { + url?.takeIf { it.isNotEmpty() }?.let { + targetUrls.add(it to forMusic) } + targetUrls.removeFirstOrNull() } - - targetUrls.removeFirstOrNull()?.let { - downloadVideo(it.first,it.second) + nextTask?.let { + downloadVideo(it.first, it.second) } - - - } + private val downloadMutex = Mutex() + @Volatile var currentProcessId : String? = null set(value) { field = value @@ -539,11 +540,13 @@ class ForeGroundService : Service() { } } + @Volatile var lastProGress = -1f fun downloadVideo(url: String?, forMusic: Boolean = false) { url?.let { - CoroutineScope(Dispatchers.IO).launch { - try { + serviceScope.launch(Dispatchers.IO) { + downloadMutex.withLock { + try { val baseDir = File(getExternalFilesDir(null), "completed_torrents") // 2. youtube 전용 폴더 생성 @@ -601,11 +604,14 @@ class ForeGroundService : Service() { Blog.LOGE("Error: ${response.err}") } catch (e: Exception) { Blog.LOGE("Download Error", e) + } finally { currentProcessId = null - if ((targetUrls?.size ?: 0) > 0) { + val hasMore = synchronized(targetUrls) { targetUrls.isNotEmpty() } + if (hasMore) { addToTargetYtubeUrl() } } + } } } } @@ -876,7 +882,7 @@ class ForeGroundService : Service() { launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) context.startActivity(launchIntent) Blog.LOGE("애플뮤직 자동 실행 완료") - CoroutineScope(Dispatchers.Main).launch { + serviceScope.launch(Dispatchers.Main) { delay(1500) // 1.5초 대기 (기기 속도에 따라 1000~2000 사이로 조절 가능) val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager