Fix DownloadService leak

pull/211/head
Koitharu 4 years ago
parent 905c4b362c
commit 22e5b958bc
No known key found for this signature in database
GPG Key ID: 8E861F8CE6E7CE27

@ -9,6 +9,8 @@ import android.os.IBinder
import android.os.PowerManager import android.os.PowerManager
import android.widget.Toast import android.widget.Toast
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
@ -43,7 +45,6 @@ class DownloadService : BaseService() {
private val jobs = LinkedHashMap<Int, PausingProgressJob<DownloadState>>() private val jobs = LinkedHashMap<Int, PausingProgressJob<DownloadState>>()
private val jobCount = MutableStateFlow(0) private val jobCount = MutableStateFlow(0)
private val controlReceiver = ControlReceiver() private val controlReceiver = ControlReceiver()
private var binder: DownloadBinder? = null
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
@ -77,17 +78,11 @@ class DownloadService : BaseService() {
override fun onBind(intent: Intent): IBinder { override fun onBind(intent: Intent): IBinder {
super.onBind(intent) super.onBind(intent)
return binder ?: DownloadBinder(this).also { binder = it } return DownloadBinder(this)
}
override fun onUnbind(intent: Intent?): Boolean {
binder = null
return super.onUnbind(intent)
} }
override fun onDestroy() { override fun onDestroy() {
unregisterReceiver(controlReceiver) unregisterReceiver(controlReceiver)
binder = null
isRunning = false isRunning = false
super.onDestroy() super.onDestroy()
} }
@ -170,10 +165,25 @@ class DownloadService : BaseService() {
} }
} }
class DownloadBinder(private val service: DownloadService) : Binder() { class DownloadBinder(service: DownloadService) : Binder(), DefaultLifecycleObserver {
private var downloadsStateFlow = MutableStateFlow<Collection<PausingProgressJob<DownloadState>>>(emptyList())
init {
service.lifecycle.addObserver(this)
service.jobCount.onEach {
downloadsStateFlow.value = service.jobs.values
}.launchIn(service.lifecycleScope)
}
override fun onDestroy(owner: LifecycleOwner) {
owner.lifecycle.removeObserver(this)
downloadsStateFlow.value = emptyList()
super.onDestroy(owner)
}
val downloads: Flow<Collection<PausingProgressJob<DownloadState>>> val downloads
get() = service.jobCount.mapLatest { service.jobs.values } get() = downloadsStateFlow.asStateFlow()
} }
companion object { companion object {

Loading…
Cancel
Save