From 62b69284a67eb15bec96be32a88271bcea624c62 Mon Sep 17 00:00:00 2001 From: Glenn Guy Date: Wed, 17 Oct 2018 22:21:19 +1100 Subject: requestAudioFocus not behaving properly Other apps were only triggering the listener if I had started dsub from Android Auto It seems that the AudioManager instance needs to come from application context rather than the service - I found the hint here: https://stackoverflow.com/a/14129015 --- .../main/java/github/daneren2005/dsub/service/DownloadService.java | 3 ++- app/src/main/java/github/daneren2005/dsub/util/Util.java | 5 +---- 2 files changed, 3 insertions(+), 5 deletions(-) (limited to 'app') diff --git a/app/src/main/java/github/daneren2005/dsub/service/DownloadService.java b/app/src/main/java/github/daneren2005/dsub/service/DownloadService.java index 605ec204..7afdd73f 100644 --- a/app/src/main/java/github/daneren2005/dsub/service/DownloadService.java +++ b/app/src/main/java/github/daneren2005/dsub/service/DownloadService.java @@ -1506,7 +1506,8 @@ public class DownloadService extends Service { this.playerState = playerState; if(playerState == STARTED) { - Util.requestAudioFocus(this); + AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE); + Util.requestAudioFocus(this, audioManager); } if (show) { diff --git a/app/src/main/java/github/daneren2005/dsub/util/Util.java b/app/src/main/java/github/daneren2005/dsub/util/Util.java index a02e7ded..78f3e2d6 100644 --- a/app/src/main/java/github/daneren2005/dsub/util/Util.java +++ b/app/src/main/java/github/daneren2005/dsub/util/Util.java @@ -1327,11 +1327,9 @@ public final class Util { } @TargetApi(8) - public static void requestAudioFocus(final Context context) { + public static void requestAudioFocus(final Context context, final AudioManager audioManager) { if(Build.VERSION.SDK_INT >= 26) { if(audioFocusRequest == null) { - final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); - AudioAttributes playbackAttributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) @@ -1344,7 +1342,6 @@ public final class Util { audioManager.requestAudioFocus(audioFocusRequest); } } else if (Build.VERSION.SDK_INT >= 8 && focusListener == null) { - final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); audioManager.requestAudioFocus(focusListener = getAudioFocusChangeListener(context, audioManager), AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); } } -- cgit v1.2.3