From ae9ebcf060f71f5dc568d9c5a4e242a7079c6adb Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Fri, 23 Oct 2026 17:28:45 -0700
Subject: [PATCH] Fixed a rare race condition shutting down Android sensors
It's possible for the thread to shutdown after running is set to false and before the looper wake happens. In that case the looper was no longer valid and Android would abort in the wake call.
---
src/sensor/android/SDL_androidsensor.c | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/src/sensor/android/SDL_androidsensor.c b/src/sensor/android/SDL_androidsensor.c
index a6fac75f1bc21..a9b8714b35f16 100644
--- a/src/sensor/android/SDL_androidsensor.c
+++ b/src/sensor/android/SDL_androidsensor.c
@@ -86,8 +86,6 @@ static int SDLCALL SDL_ANDROID_SensorThread(void *data)
}
}
- SDL_sensor_looper = NULL;
-
return 0;
}
@@ -105,6 +103,11 @@ static void SDL_ANDROID_StopSensorThread(SDL_AndroidSensorThreadContext *ctx)
ctx->thread = NULL;
}
+ if (SDL_sensor_looper) {
+ ALooper_release(SDL_sensor_looper);
+ SDL_sensor_looper = NULL;
+ }
+
if (ctx->sem) {
SDL_DestroySemaphore(ctx->sem);
ctx->sem = NULL;
@@ -129,6 +132,9 @@ static bool SDL_ANDROID_StartSensorThread(SDL_AndroidSensorThreadContext *ctx)
// Wait for the sensor thread to start
SDL_WaitSemaphore(ctx->sem);
+ // Hold a reference to the sensor thread's looper so it stays valid until the thread has been stopped
+ ALooper_acquire(SDL_sensor_looper);
+
return true;
}