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:
@@ -32,6 +32,7 @@ import android.widget.Toast
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
@@ -121,9 +122,12 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var recyclerView: RecyclerView
|
||||
private lateinit var adapter: CompletedFilesAdapter
|
||||
private lateinit var completedRootDir: File
|
||||
private lateinit var tempRootDir: File
|
||||
private lateinit var rootDir: File
|
||||
private lateinit var currentDir: File
|
||||
private var allFiles = listOf<File>()
|
||||
private var isViewingTempDir = false
|
||||
|
||||
private var currentFilter = FileFilterType.ALL
|
||||
private var currentSort = FileSortType.LAST_USED
|
||||
@@ -155,8 +159,9 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.fragment_completed_files)
|
||||
|
||||
rootDir = File(getExternalFilesDir(null), "completed_torrents")
|
||||
if (!rootDir.exists()) rootDir.mkdirs()
|
||||
completedRootDir = File(getExternalFilesDir(null), "completed_torrents").apply { if (!exists()) mkdirs() }
|
||||
tempRootDir = File(getExternalFilesDir(null), "temp_torrents").apply { if (!exists()) mkdirs() }
|
||||
rootDir = completedRootDir
|
||||
currentDir = rootDir
|
||||
|
||||
geckoWeb = findViewById(R.id.geckoWebFragment)
|
||||
@@ -190,12 +195,10 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
private fun updateSelectionUI() {
|
||||
adapter.updateSelection(selectedFiles)
|
||||
|
||||
// 1. 미리보기 버튼: 전체 선택이 딱 1개이고, 그 파일이 영상일 때만 노출
|
||||
val singleFile = selectedFiles.singleOrNull()
|
||||
val isSingleVideo = singleFile != null && singleFile.isFile && extVideos.contains(singleFile.extension.lowercase())
|
||||
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 btnSub = findViewById<TextView>(R.id.btnSearchSubtitle)
|
||||
if (videoCount > 0) {
|
||||
@@ -282,8 +285,6 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
return ""
|
||||
}
|
||||
|
||||
// --- 자막 검색 & 일괄 처리 큐 파이프라인 ---
|
||||
|
||||
private fun startSubtitleSearchQueue(videoFiles: List<File>) {
|
||||
if (videoFiles.isEmpty()) return
|
||||
|
||||
@@ -391,10 +392,10 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
val targetDir = videoFile.parentFile
|
||||
val newSubFile = File(targetDir, "${videoFile.nameWithoutExtension}.srt")
|
||||
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
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) {
|
||||
response.body?.byteStream()?.use { input ->
|
||||
@@ -414,6 +415,7 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
if (isBatchSubtitleMode) processNextSubtitleInQueue()
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
withContext(Dispatchers.Main) {
|
||||
Toast.makeText(this@CompletedFilesActivity, "자막 다운로드 실패: ${e.message}", Toast.LENGTH_SHORT).show()
|
||||
@@ -536,7 +538,7 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
|
||||
translator.downloadModelIfNeeded()
|
||||
.addOnSuccessListener {
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
for (block in subtitles) {
|
||||
try {
|
||||
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()
|
||||
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
var copyCount = 0
|
||||
filesToCopy.forEach { file ->
|
||||
try {
|
||||
@@ -839,6 +841,8 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
private fun setupControls() {
|
||||
val layoutTitleDefault = findViewById<View>(R.id.layoutTitleDefault)
|
||||
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 btnSearch = findViewById<TextView>(R.id.btnSearch)
|
||||
val btnCloseSearch = findViewById<TextView>(R.id.btnCloseSearch)
|
||||
@@ -848,6 +852,28 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
val btnViewMode = findViewById<TextView>(R.id.btnViewMode)
|
||||
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 {
|
||||
layoutTitleDefault.visibility = View.GONE
|
||||
layoutTitleSearch.visibility = View.VISIBLE
|
||||
@@ -857,7 +883,7 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
imm.showSoftInput(etSearch, InputMethodManager.SHOW_IMPLICIT)
|
||||
}, 100)
|
||||
}
|
||||
findViewById<View>(R.id.tvTitle)?.setOnClickListener { btnSearch.performClick() }
|
||||
tvTitle?.setOnClickListener { btnSearch.performClick() }
|
||||
|
||||
btnCloseSearch.setOnClickListener {
|
||||
searchQuery = ""
|
||||
@@ -1143,7 +1169,8 @@ class CompletedFilesActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
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 trashDir = File(rootDir, "trash").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")
|
||||
|
||||
private fun isProtectedFolder(file: File): Boolean {
|
||||
if (isViewingTempDir) return false
|
||||
return file.isDirectory && file.parentFile == rootDir && protectedFolders.contains(file.name)
|
||||
}
|
||||
|
||||
private fun isProtectedFile(file: File): Boolean {
|
||||
if (isViewingTempDir) return false
|
||||
if (file.isDirectory && file.parentFile == rootDir && protectedFolders.contains(file.name)) return true
|
||||
val parent = file.parentFile
|
||||
if (parent != null && parent.parentFile == rootDir && protectedFolders.contains(parent.name)) return true
|
||||
@@ -1424,7 +1453,7 @@ class VideoPreviewHelper(
|
||||
) {
|
||||
private var extractJob: Job? = null
|
||||
|
||||
fun showPreviewDialog(videoFile: File, targetFrameCount: Int = 15) {
|
||||
fun showPreviewDialog(videoFile: File, targetFrameCount: Int = 30) {
|
||||
val dialog = BottomSheetDialog(context)
|
||||
|
||||
val container = LinearLayout(context).apply {
|
||||
@@ -1452,7 +1481,7 @@ class VideoPreviewHelper(
|
||||
layoutManager = GridLayoutManager(context, 3)
|
||||
layoutParams = ViewGroup.LayoutParams(
|
||||
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()
|
||||
|
||||
extractJob = CoroutineScope(Dispatchers.IO).launch {
|
||||
val scope = (context as? androidx.lifecycle.LifecycleOwner)?.lifecycleScope ?: CoroutineScope(Dispatchers.IO)
|
||||
extractJob = scope.launch(Dispatchers.IO) {
|
||||
val retriever = MediaMetadataRetriever()
|
||||
try {
|
||||
retriever.setDataSource(videoFile.absolutePath)
|
||||
@@ -1496,7 +1526,7 @@ class VideoPreviewHelper(
|
||||
|
||||
if (durationMs <= 0L) {
|
||||
withContext(Dispatchers.Main) {
|
||||
Toast.makeText(context, "영상 길이 정보를 읽을 수 없습니다.", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, "영상 길이 정보를 읽을 수 없습니다. (다운로드 초반일 수 있음)", Toast.LENGTH_SHORT).show()
|
||||
dialog.dismiss()
|
||||
}
|
||||
return@launch
|
||||
|
||||
@@ -39,6 +39,7 @@ import java.util.Calendar
|
||||
class NLService : NotificationListenerService() {
|
||||
private val TAG: String = this.javaClass.simpleName
|
||||
private var nlservicereciver: NLServiceReceiver? = null
|
||||
private val serviceScope = CoroutineScope(Dispatchers.IO + kotlinx.coroutines.SupervisorJob())
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
@@ -48,8 +49,11 @@ class NLService : NotificationListenerService() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
try {
|
||||
unregisterReceiver(nlservicereciver)
|
||||
} catch (_: Exception) { }
|
||||
serviceScope.coroutineContext[kotlinx.coroutines.Job]?.cancel()
|
||||
super.onDestroy()
|
||||
unregisterReceiver(nlservicereciver)
|
||||
}
|
||||
|
||||
|
||||
@@ -183,7 +187,7 @@ class NLService : NotificationListenerService() {
|
||||
private val fileWriteLock = Any()
|
||||
|
||||
private fun saveNotificationToFile(packageName: String, content: String) {
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
serviceScope.launch {
|
||||
try {
|
||||
val now = Date()
|
||||
val calendar = Calendar.getInstance().apply { time = now }
|
||||
|
||||
Reference in New Issue
Block a user