[Android] Prevent scheduler crashes when trying to schedule a task after timer cancellation

Nicolas Pomepuy git at videolan.org
Tue Jul 25 14:57:29 UTC 2023


vlc-android | branch: master | Nicolas Pomepuy <nicolas at videolabs.io> | Fri Jul 21 08:16:07 2023 +0200| [80ace3531fe512d7ad81a751467f05a284bb0a7b] | committer: Duncan McNamara

Prevent scheduler crashes when trying to schedule a task after timer cancellation

> https://code.videolan.org/videolan/vlc-android/commit/80ace3531fe512d7ad81a751467f05a284bb0a7b
---

 .../vlc-android/src/org/videolan/vlc/util/LifecycleAwareScheduler.kt  | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/application/vlc-android/src/org/videolan/vlc/util/LifecycleAwareScheduler.kt b/application/vlc-android/src/org/videolan/vlc/util/LifecycleAwareScheduler.kt
index 4c07060afb..4979f440c4 100644
--- a/application/vlc-android/src/org/videolan/vlc/util/LifecycleAwareScheduler.kt
+++ b/application/vlc-android/src/org/videolan/vlc/util/LifecycleAwareScheduler.kt
@@ -69,6 +69,7 @@ interface SchedulerCallback : LifecycleOwner {
  */
 class LifecycleAwareScheduler(private val callback: SchedulerCallback) : DefaultLifecycleObserver {
 
+    private var canceled: Boolean = false
     private val timer = Timer()
     private val timeTasks = HashMap<String, TimerTask>()
 
@@ -96,6 +97,7 @@ class LifecycleAwareScheduler(private val callback: SchedulerCallback) : Default
      * @param data the data to be passed
      */
     fun scheduleAction(id: String, delay: Long, data:Bundle = Bundle()) {
+        if (canceled) return
         if (BuildConfig.DEBUG) Log.d("LifecycleAwareScheduler", "Scheduling action for $callback on thread ${Thread.currentThread()} with id $id")
         callback.lifecycle.addObserver(this at LifecycleAwareScheduler)
         if (timeTasks.keys.contains(id)) cancelAction(id)
@@ -114,6 +116,7 @@ class LifecycleAwareScheduler(private val callback: SchedulerCallback) : Default
      * @param data the data to be passed
      */
     fun scheduleAtFixedRate(id: String, interval: Long, data:Bundle = Bundle()) {
+        if (canceled) return
         callback.lifecycle.addObserver(this at LifecycleAwareScheduler)
         if (timeTasks.keys.contains(id)) cancelAction(id)
         timeTasks[id] = timerTask {
@@ -144,6 +147,7 @@ class LifecycleAwareScheduler(private val callback: SchedulerCallback) : Default
      */
     private fun discardTimer() {
         timeTasks.forEach { callback.onTaskCanceled(it.key) }
+        canceled = true
         timer.cancel()
         callback.lifecycle.removeObserver(this)
     }



More information about the Android mailing list