fix: Task 11 완료 - CompletedFilesActivity 및 NLService 코루틴 생명주기 관리 전환

- CompletedFilesActivity.kt:
  * 비관리 CoroutineScope(Dispatchers.IO).launch 호출부들을 lifecycleScope.launch(Dispatchers.IO) (및 top-level 다이얼로그 헬퍼는 LifecycleOwner 우선 폴백)로 전환
  * 자막 다운로드 시 공용 NetworkClient.client 및 Response.use {} 적용
- NLService.kt:
  * SupervisorJob 기반 serviceScope 도입 및 saveNotificationToFile()에서 serviceScope.launch 사용
  * onDestroy()에서 unregisterReceiver 예외 방어 및 serviceScope Job 취소 추가
- 검증: ./gradlew :app:compileDebugKotlin 빌드 성공 확인 (7s)
This commit is contained in:
2026-11-16 11:24:15 +09:00
parent 6570929608
commit a0bc32cb95
2 changed files with 52 additions and 18 deletions
@@ -32,6 +32,7 @@ import android.widget.Toast
import androidx.activity.OnBackPressedCallback import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.core.content.FileProvider import androidx.core.content.FileProvider
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
@@ -121,9 +122,12 @@ class CompletedFilesActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView private lateinit var recyclerView: RecyclerView
private lateinit var adapter: CompletedFilesAdapter private lateinit var adapter: CompletedFilesAdapter
private lateinit var completedRootDir: File
private lateinit var tempRootDir: File
private lateinit var rootDir: File private lateinit var rootDir: File
private lateinit var currentDir: File private lateinit var currentDir: File
private var allFiles = listOf<File>() private var allFiles = listOf<File>()
private var isViewingTempDir = false
private var currentFilter = FileFilterType.ALL private var currentFilter = FileFilterType.ALL
private var currentSort = FileSortType.LAST_USED private var currentSort = FileSortType.LAST_USED
@@ -155,8 +159,9 @@ class CompletedFilesActivity : AppCompatActivity() {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_completed_files) setContentView(R.layout.fragment_completed_files)
rootDir = File(getExternalFilesDir(null), "completed_torrents") completedRootDir = File(getExternalFilesDir(null), "completed_torrents").apply { if (!exists()) mkdirs() }
if (!rootDir.exists()) rootDir.mkdirs() tempRootDir = File(getExternalFilesDir(null), "temp_torrents").apply { if (!exists()) mkdirs() }
rootDir = completedRootDir
currentDir = rootDir currentDir = rootDir
geckoWeb = findViewById(R.id.geckoWebFragment) geckoWeb = findViewById(R.id.geckoWebFragment)
@@ -190,12 +195,10 @@ class CompletedFilesActivity : AppCompatActivity() {
private fun updateSelectionUI() { private fun updateSelectionUI() {
adapter.updateSelection(selectedFiles) adapter.updateSelection(selectedFiles)
// 1. 미리보기 버튼: 전체 선택이 딱 1개이고, 그 파일이 영상일 때만 노출
val singleFile = selectedFiles.singleOrNull() val singleFile = selectedFiles.singleOrNull()
val isSingleVideo = singleFile != null && singleFile.isFile && extVideos.contains(singleFile.extension.lowercase()) val isSingleVideo = singleFile != null && singleFile.isFile && extVideos.contains(singleFile.extension.lowercase())
findViewById<View>(R.id.btnVideoPreview)?.visibility = if (isSingleVideo) View.VISIBLE else View.GONE findViewById<View>(R.id.btnVideoPreview)?.visibility = if (isSingleVideo) View.VISIBLE else View.GONE
// 2. 자막 검색 버튼: 영상 파일이 1개 이상 선택되었을 때 노출
val videoCount = selectedFiles.count { it.isFile && extVideos.contains(it.extension.lowercase()) } val videoCount = selectedFiles.count { it.isFile && extVideos.contains(it.extension.lowercase()) }
val btnSub = findViewById<TextView>(R.id.btnSearchSubtitle) val btnSub = findViewById<TextView>(R.id.btnSearchSubtitle)
if (videoCount > 0) { if (videoCount > 0) {
@@ -282,8 +285,6 @@ class CompletedFilesActivity : AppCompatActivity() {
return "" return ""
} }
// --- 자막 검색 & 일괄 처리 큐 파이프라인 ---
private fun startSubtitleSearchQueue(videoFiles: List<File>) { private fun startSubtitleSearchQueue(videoFiles: List<File>) {
if (videoFiles.isEmpty()) return if (videoFiles.isEmpty()) return
@@ -391,10 +392,10 @@ class CompletedFilesActivity : AppCompatActivity() {
val targetDir = videoFile.parentFile val targetDir = videoFile.parentFile
val newSubFile = File(targetDir, "${videoFile.nameWithoutExtension}.srt") val newSubFile = File(targetDir, "${videoFile.nameWithoutExtension}.srt")
CoroutineScope(Dispatchers.IO).launch { lifecycleScope.launch(Dispatchers.IO) {
try { try {
val request = okhttp3.Request.Builder().url(url).build() val request = okhttp3.Request.Builder().url(url).build()
val response = okhttp3.OkHttpClient().newCall(request).execute() bums.lunatic.launcher.utils.NetworkClient.client.newCall(request).execute().use { response ->
if (response.isSuccessful) { if (response.isSuccessful) {
response.body?.byteStream()?.use { input -> response.body?.byteStream()?.use { input ->
@@ -414,6 +415,7 @@ class CompletedFilesActivity : AppCompatActivity() {
if (isBatchSubtitleMode) processNextSubtitleInQueue() if (isBatchSubtitleMode) processNextSubtitleInQueue()
} }
} }
}
} catch (e: Exception) { } catch (e: Exception) {
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
Toast.makeText(this@CompletedFilesActivity, "자막 다운로드 실패: ${e.message}", Toast.LENGTH_SHORT).show() Toast.makeText(this@CompletedFilesActivity, "자막 다운로드 실패: ${e.message}", Toast.LENGTH_SHORT).show()
@@ -536,7 +538,7 @@ class CompletedFilesActivity : AppCompatActivity() {
translator.downloadModelIfNeeded() translator.downloadModelIfNeeded()
.addOnSuccessListener { .addOnSuccessListener {
CoroutineScope(Dispatchers.IO).launch { lifecycleScope.launch(Dispatchers.IO) {
for (block in subtitles) { for (block in subtitles) {
try { try {
val translated = com.google.android.gms.tasks.Tasks.await(translator.translate(block.text)) val translated = com.google.android.gms.tasks.Tasks.await(translator.translate(block.text))
@@ -764,7 +766,7 @@ class CompletedFilesActivity : AppCompatActivity() {
Toast.makeText(this, "다운로드 폴더로 복사를 시작합니다...", Toast.LENGTH_SHORT).show() Toast.makeText(this, "다운로드 폴더로 복사를 시작합니다...", Toast.LENGTH_SHORT).show()
CoroutineScope(Dispatchers.IO).launch { lifecycleScope.launch(Dispatchers.IO) {
var copyCount = 0 var copyCount = 0
filesToCopy.forEach { file -> filesToCopy.forEach { file ->
try { try {
@@ -839,6 +841,8 @@ class CompletedFilesActivity : AppCompatActivity() {
private fun setupControls() { private fun setupControls() {
val layoutTitleDefault = findViewById<View>(R.id.layoutTitleDefault) val layoutTitleDefault = findViewById<View>(R.id.layoutTitleDefault)
val layoutTitleSearch = findViewById<View>(R.id.layoutTitleSearch) val layoutTitleSearch = findViewById<View>(R.id.layoutTitleSearch)
val tvTitle = findViewById<TextView>(R.id.tvTitle)
val btnToggleTempDir = findViewById<TextView>(R.id.btnToggleTempDir)
val etSearch = findViewById<EditText>(R.id.etSearch) val etSearch = findViewById<EditText>(R.id.etSearch)
val btnSearch = findViewById<TextView>(R.id.btnSearch) val btnSearch = findViewById<TextView>(R.id.btnSearch)
val btnCloseSearch = findViewById<TextView>(R.id.btnCloseSearch) val btnCloseSearch = findViewById<TextView>(R.id.btnCloseSearch)
@@ -848,6 +852,28 @@ class CompletedFilesActivity : AppCompatActivity() {
val btnViewMode = findViewById<TextView>(R.id.btnViewMode) val btnViewMode = findViewById<TextView>(R.id.btnViewMode)
val btnOrganize = findViewById<TextView>(R.id.btnOrganize) val btnOrganize = findViewById<TextView>(R.id.btnOrganize)
btnToggleTempDir?.setOnClickListener {
if (isSelectionMode) toggleSelectionMode(false)
isViewingTempDir = !isViewingTempDir
if (isViewingTempDir) {
rootDir = tempRootDir
currentDir = tempRootDir
tvTitle?.text = "다운로드 중 (임시)"
btnToggleTempDir.text = "보관함으로"
btnToggleTempDir.setTextColor(Color.parseColor("#00A8FF"))
btnOrganize?.visibility = View.GONE
} else {
rootDir = completedRootDir
currentDir = completedRootDir
tvTitle?.text = "다운로드 보관함"
btnToggleTempDir.text = "진행중 폴더"
btnToggleTempDir.setTextColor(Color.parseColor("#FF9800"))
btnOrganize?.visibility = View.VISIBLE
}
loadFiles()
}
btnSearch.setOnClickListener { btnSearch.setOnClickListener {
layoutTitleDefault.visibility = View.GONE layoutTitleDefault.visibility = View.GONE
layoutTitleSearch.visibility = View.VISIBLE layoutTitleSearch.visibility = View.VISIBLE
@@ -857,7 +883,7 @@ class CompletedFilesActivity : AppCompatActivity() {
imm.showSoftInput(etSearch, InputMethodManager.SHOW_IMPLICIT) imm.showSoftInput(etSearch, InputMethodManager.SHOW_IMPLICIT)
}, 100) }, 100)
} }
findViewById<View>(R.id.tvTitle)?.setOnClickListener { btnSearch.performClick() } tvTitle?.setOnClickListener { btnSearch.performClick() }
btnCloseSearch.setOnClickListener { btnCloseSearch.setOnClickListener {
searchQuery = "" searchQuery = ""
@@ -1143,7 +1169,8 @@ class CompletedFilesActivity : AppCompatActivity() {
} }
private fun organizeRootFiles() { private fun organizeRootFiles() {
CoroutineScope(Dispatchers.IO).launch { if (isViewingTempDir) return
lifecycleScope.launch(Dispatchers.IO) {
val filesInRoot = if (selectedFiles.isEmpty()) rootDir.listFiles()?.filter { it.isFile } else selectedFiles val filesInRoot = if (selectedFiles.isEmpty()) rootDir.listFiles()?.filter { it.isFile } else selectedFiles
val trashDir = File(rootDir, "trash").apply { if (!exists()) mkdirs() } val trashDir = File(rootDir, "trash").apply { if (!exists()) mkdirs() }
val videoTargetDir = File(rootDir, "Videos").apply { if (!exists()) mkdirs() } val videoTargetDir = File(rootDir, "Videos").apply { if (!exists()) mkdirs() }
@@ -1224,10 +1251,12 @@ class CompletedFilesActivity : AppCompatActivity() {
val protectedFolders = setOf("Images", "Videos", "Youtube") val protectedFolders = setOf("Images", "Videos", "Youtube")
private fun isProtectedFolder(file: File): Boolean { private fun isProtectedFolder(file: File): Boolean {
if (isViewingTempDir) return false
return file.isDirectory && file.parentFile == rootDir && protectedFolders.contains(file.name) return file.isDirectory && file.parentFile == rootDir && protectedFolders.contains(file.name)
} }
private fun isProtectedFile(file: File): Boolean { private fun isProtectedFile(file: File): Boolean {
if (isViewingTempDir) return false
if (file.isDirectory && file.parentFile == rootDir && protectedFolders.contains(file.name)) return true if (file.isDirectory && file.parentFile == rootDir && protectedFolders.contains(file.name)) return true
val parent = file.parentFile val parent = file.parentFile
if (parent != null && parent.parentFile == rootDir && protectedFolders.contains(parent.name)) return true if (parent != null && parent.parentFile == rootDir && protectedFolders.contains(parent.name)) return true
@@ -1424,7 +1453,7 @@ class VideoPreviewHelper(
) { ) {
private var extractJob: Job? = null private var extractJob: Job? = null
fun showPreviewDialog(videoFile: File, targetFrameCount: Int = 15) { fun showPreviewDialog(videoFile: File, targetFrameCount: Int = 30) {
val dialog = BottomSheetDialog(context) val dialog = BottomSheetDialog(context)
val container = LinearLayout(context).apply { val container = LinearLayout(context).apply {
@@ -1452,7 +1481,7 @@ class VideoPreviewHelper(
layoutManager = GridLayoutManager(context, 3) layoutManager = GridLayoutManager(context, 3)
layoutParams = ViewGroup.LayoutParams( layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
(context.resources.displayMetrics.heightPixels * 0.65).toInt() (context.resources.displayMetrics.heightPixels * 0.70).toInt()
) )
} }
@@ -1486,7 +1515,8 @@ class VideoPreviewHelper(
dialog.show() dialog.show()
extractJob = CoroutineScope(Dispatchers.IO).launch { val scope = (context as? androidx.lifecycle.LifecycleOwner)?.lifecycleScope ?: CoroutineScope(Dispatchers.IO)
extractJob = scope.launch(Dispatchers.IO) {
val retriever = MediaMetadataRetriever() val retriever = MediaMetadataRetriever()
try { try {
retriever.setDataSource(videoFile.absolutePath) retriever.setDataSource(videoFile.absolutePath)
@@ -1496,7 +1526,7 @@ class VideoPreviewHelper(
if (durationMs <= 0L) { if (durationMs <= 0L) {
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
Toast.makeText(context, "영상 길이 정보를 읽을 수 없습니다.", Toast.LENGTH_SHORT).show() Toast.makeText(context, "영상 길이 정보를 읽을 수 없습니다. (다운로드 초반일 수 있음)", Toast.LENGTH_SHORT).show()
dialog.dismiss() dialog.dismiss()
} }
return@launch return@launch
@@ -39,6 +39,7 @@ import java.util.Calendar
class NLService : NotificationListenerService() { class NLService : NotificationListenerService() {
private val TAG: String = this.javaClass.simpleName private val TAG: String = this.javaClass.simpleName
private var nlservicereciver: NLServiceReceiver? = null private var nlservicereciver: NLServiceReceiver? = null
private val serviceScope = CoroutineScope(Dispatchers.IO + kotlinx.coroutines.SupervisorJob())
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
@@ -48,8 +49,11 @@ class NLService : NotificationListenerService() {
} }
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() try {
unregisterReceiver(nlservicereciver) unregisterReceiver(nlservicereciver)
} catch (_: Exception) { }
serviceScope.coroutineContext[kotlinx.coroutines.Job]?.cancel()
super.onDestroy()
} }
@@ -183,7 +187,7 @@ class NLService : NotificationListenerService() {
private val fileWriteLock = Any() private val fileWriteLock = Any()
private fun saveNotificationToFile(packageName: String, content: String) { private fun saveNotificationToFile(packageName: String, content: String) {
CoroutineScope(Dispatchers.IO).launch { serviceScope.launch {
try { try {
val now = Date() val now = Date()
val calendar = Calendar.getInstance().apply { time = now } val calendar = Calendar.getInstance().apply { time = now }