diff --git a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskContext.java b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskContext.java index 1304ef07e..ff1ffe8f1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskContext.java +++ b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskContext.java @@ -93,12 +93,12 @@ public class HeadlessJsTaskContext { " while in foreground, but this is not allowed."); } final int taskId = mLastTaskId.incrementAndGet(); + mActiveTasks.add(taskId); reactContext.getJSModule(AppRegistry.class) .startHeadlessTask(taskId, taskConfig.getTaskKey(), taskConfig.getData()); if (taskConfig.getTimeout() > 0) { scheduleTaskTimeout(taskId, taskConfig.getTimeout()); } - mActiveTasks.add(taskId); for (HeadlessJsTaskEventListener listener : mHeadlessJsTaskEventListeners) { listener.onHeadlessJsTaskStart(taskId); } @@ -107,7 +107,7 @@ public class HeadlessJsTaskContext { /** * Finish a JS task. Doesn't actually stop the task on the JS side, only removes it from the list - * of active tasks and notifies listeners. + * of active tasks and notifies listeners. A task can only be finished once. * * @param taskId the unique id returned by {@link #startTask}. */ @@ -130,6 +130,14 @@ public class HeadlessJsTaskContext { }); } + /** + * Check if a given task is currently running. A task is stopped if either {@link #finishTask} is + * called or it times out. + */ + public synchronized boolean isTaskRunning(final int taskId) { + return mActiveTasks.contains(taskId); + } + private void scheduleTaskTimeout(final int taskId, long timeout) { Runnable runnable = new Runnable() { @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/HeadlessJsTaskSupportModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/HeadlessJsTaskSupportModule.java index 3e8df3a36..5f4c0799d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/HeadlessJsTaskSupportModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/HeadlessJsTaskSupportModule.java @@ -9,6 +9,7 @@ package com.facebook.react.modules.core; +import com.facebook.common.logging.FLog; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; @@ -37,6 +38,13 @@ public class HeadlessJsTaskSupportModule extends ReactContextBaseJavaModule { public void notifyTaskFinished(int taskId) { HeadlessJsTaskContext headlessJsTaskContext = HeadlessJsTaskContext.getInstance(getReactApplicationContext()); - headlessJsTaskContext.finishTask(taskId); + if (headlessJsTaskContext.isTaskRunning(taskId)) { + headlessJsTaskContext.finishTask(taskId); + } else { + FLog.w( + HeadlessJsTaskSupportModule.class, + "Tried to finish non-active task with id %d. Did it time out?", + taskId); + } } }