A cross platform Audiobookshelf client for Android and iOS
Dart
Stop dropping headphone play presses that arrive as a pause while already paused, unless Android Auto is connected
Barnabas7e7623a416cf
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex af6bc329..ab9fd048 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -106,7 +106,8 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {'[AbsorbDiag] $tag: ''keyCode=${snap['lastKeyCode']} keyAgeMs=${snap['lastKeyAgeMs']} ''lastPlayCaller=${snap['lastPlayCaller']} playAgeMs=${snap['lastPlayCallerAgeMs']} '- 'lastPauseCaller=${snap['lastPauseCaller']} pauseAgeMs=${snap['lastPauseCallerAgeMs']}',+ 'lastPauseCaller=${snap['lastPauseCaller']} pauseAgeMs=${snap['lastPauseCallerAgeMs']} '+ 'carClientAgeMs=${snap['carClientAgeMs']}',);}@@ -114,6 +115,28 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {_logAbsorbDiagFromSnapshot(tag, await _absorbDiagSnapshot());}+ /// How long after a car client (Android Auto / Automotive) last touched the+ /// browse tree we still assume a car is attached. Long enough to span a+ /// drive where the head unit connected once and never browsed again, short+ /// enough that a headset press hours after the drive is taken at face value.+ static const _carClientWindow = Duration(hours: 2);++ /// Whether a car client has touched the media browse tree recently, per the+ /// Java-side stamp. The MEDIA_PAUSE-while-paused phantom (GH #243) only+ /// exists on Android Auto, so this is what decides whether the click+ /// resolver suppresses that keycode or honors it as a headset toggle.+ /// Snapshot missing (iOS, channel unavailable) reads as no car.+ static Future<bool> _carClientRecentlySeen() async {+ final snap = await _absorbDiagSnapshot();+ final age = snap?['carClientAgeMs'];+ final seen =+ age is int && age >= 0 && age < _carClientWindow.inMilliseconds;+ debugPrint(+ '[Handler] car client ${seen ? 'seen' : 'not seen'} (carClientAgeMs=$age)',+ );+ return seen;+ }+/// Force-push current PlaybackState so the notification picks up/// new chapter-relative position immediately (e.g. on chapter change).void refreshPlaybackState() {@@ -813,10 +836,19 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {if (_player.playing) {debugPrint('[Handler] → single press (MEDIA_PAUSE) → PAUSE');await pause();+ } else if (await _carClientRecentlySeen()) {+ debugPrint(+ '[Handler] -> single press (MEDIA_PAUSE while paused) -> no-op (suppressed phantom toggle to PLAY, car client seen)',+ );} else {+ // Some BT headsets (Shokz seen in the wild) send MEDIA_PAUSE+ // for a play press when their idea of our state went stale.+ // Without a car around there is no #243 phantom to guard+ // against, so treat it as the toggle the user meant.debugPrint(- '[Handler] → single press (MEDIA_PAUSE while paused) → no-op (suppressed phantom toggle to PLAY)',+ '[Handler] -> single press (MEDIA_PAUSE while paused, no car client) -> PLAY',);+ await play();}} else if (kc == keycodeMediaPlay) {if (!_player.playing) {diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.javaindex acdd65f6..a48d0e06 100644--- a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java@@ -111,6 +111,19 @@ public class AudioService extends MediaBrowserServiceCompat {private static volatile long lastMediaKeyAt = 0;private static volatile long lastPlayAt = 0;private static volatile long lastPauseAt = 0;+ // Stamped whenever a car client (Android Auto / Automotive) touches the+ // browse tree, so the Dart side can tell an AA phantom MEDIA_PAUSE from a+ // headset toggle that arrived while paused.+ private static volatile long lastCarClientAt = 0;++ private static boolean isCarPackage(String pkg) {+ return pkg != null && (pkg.equals("com.google.android.projection.gearhead")+ || pkg.startsWith("com.android.car"));+ }++ static void stampCarClient(String pkg) {+ if (isCarPackage(pkg)) lastCarClientAt = SystemClock.elapsedRealtime();+ }public static Map<String, Object> getDiagnosticSnapshot() {final long now = SystemClock.elapsedRealtime();@@ -121,6 +134,7 @@ public class AudioService extends MediaBrowserServiceCompat {snapshot.put("lastPlayCallerAgeMs", lastPlayAt == 0 ? -1 : now - lastPlayAt);snapshot.put("lastPauseCaller", "mediaSession");snapshot.put("lastPauseCallerAgeMs", lastPauseAt == 0 ? -1 : now - lastPauseAt);+ snapshot.put("carClientAgeMs", lastCarClientAt == 0 ? -1 : now - lastCarClientAt);return snapshot;}@@ -867,6 +881,7 @@ public class AudioService extends MediaBrowserServiceCompat {@Overridepublic BrowserRoot onGetRoot(String clientPackageName, int clientUid, Bundle rootHints) {+ stampCarClient(clientPackageName);Boolean isRecentRequest = rootHints == null ? null : (Boolean)rootHints.getBoolean(BrowserRoot.EXTRA_RECENT);if (isRecentRequest == null) isRecentRequest = false;Bundle extras = config.getBrowsableRootExtras();@@ -884,6 +899,11 @@ public class AudioService extends MediaBrowserServiceCompat {@Overridepublic void onLoadChildren(final String parentMediaId, final Result<List<MediaBrowserCompat.MediaItem>> result, Bundle options) {+ // Keeps the car stamp fresh through a long drive - AA re-queries the+ // tree whenever we notify children changed.+ try {+ stampCarClient(getCurrentBrowserInfo().getPackageName());+ } catch (Exception ignored) {}if (listener == null) {result.sendResult(new ArrayList<>());return;@@ -968,9 +988,21 @@ public class AudioService extends MediaBrowserServiceCompat {listener.onPrepareFromUri(uri, extras);}+ // Also stamps the car client when Android Auto itself sends the+ // command, so a long drive with no browsing keeps the stamp fresh+ // right up to the head-unit pause that precedes the phantom. Only+ // valid inside a Callback method; headset presses arrive via the+ // system and never match a car package.+ private void stampCarController() {+ try {+ stampCarClient(mediaSession.getCurrentControllerInfo().getPackageName());+ } catch (Exception ignored) {}+ }+@Overridepublic void onPlay() {if (listener == null) return;+ stampCarController();lastPlayAt = SystemClock.elapsedRealtime();listener.onPlay();}@@ -1000,6 +1032,7 @@ public class AudioService extends MediaBrowserServiceCompat {@SuppressWarnings("deprecation")final KeyEvent event = (KeyEvent)mediaButtonEvent.getExtras().getParcelable(Intent.EXTRA_KEY_EVENT);if (event.getAction() == KeyEvent.ACTION_DOWN) {+ stampCarController();lastMediaKeyCode = event.getKeyCode();lastMediaKeyAt = SystemClock.elapsedRealtime();switch (event.getKeyCode()) {@@ -1057,6 +1090,7 @@ public class AudioService extends MediaBrowserServiceCompat {@Overridepublic void onPause() {if (listener == null) return;+ stampCarController();lastPauseAt = SystemClock.elapsedRealtime();listener.onPause();}