music: move automatic reloading to musikr
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package org.oxycblt.musikr.track
|
||||
|
||||
import android.content.Context
|
||||
import android.database.ContentObserver
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
|
||||
internal class LocationObserver(
|
||||
private val context: Context,
|
||||
private val location: MusicLocation,
|
||||
private val listener: UpdateTracker.Callback
|
||||
) : ContentObserver(Handler(Looper.getMainLooper())), Runnable {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
init {
|
||||
context.applicationContext.contentResolver.registerContentObserver(
|
||||
location.uri,
|
||||
true,
|
||||
this
|
||||
)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
handler.removeCallbacks(this)
|
||||
context.applicationContext.contentResolver.unregisterContentObserver(this)
|
||||
}
|
||||
|
||||
override fun onChange(selfChange: Boolean) {
|
||||
// Batch rapid-fire updates into a single callback after delay
|
||||
handler.removeCallbacks(this)
|
||||
handler.postDelayed(this, REINDEX_DELAY_MS)
|
||||
}
|
||||
|
||||
override fun run() {
|
||||
listener.onUpdate(location)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val REINDEX_DELAY_MS = 500L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package org.oxycblt.musikr.track
|
||||
|
||||
import android.content.Context
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
|
||||
interface UpdateTracker {
|
||||
fun track(locations: List<MusicLocation>)
|
||||
|
||||
fun release()
|
||||
|
||||
interface Callback {
|
||||
fun onUpdate(location: MusicLocation)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun from(context: Context, callback: Callback): UpdateTracker = UpdateTrackerImpl(context, callback)
|
||||
}
|
||||
}
|
||||
|
||||
private class UpdateTrackerImpl(
|
||||
private val context: Context,
|
||||
private val callback: UpdateTracker.Callback
|
||||
) : UpdateTracker {
|
||||
private val observers = mutableListOf<LocationObserver>()
|
||||
|
||||
override fun track(locations: List<MusicLocation>) {
|
||||
release()
|
||||
observers.addAll(locations.map { LocationObserver(context, it, callback) })
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
observers.forEach { it.release() }
|
||||
observers.clear()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user