From 9c6c18912f8fa98ff286fb2f1769034ec4e89f65 Mon Sep 17 00:00:00 2001 From: Adrian Ulrich Date: Mon, 11 Dec 2017 19:38:41 +0100 Subject: [PATCH] Use `AudioDeviceInfo` on newer android devices to detect if headphones or headsets are connected. --- .../android/vanilla/PlaybackService.java | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/src/ch/blinkenlights/android/vanilla/PlaybackService.java b/src/ch/blinkenlights/android/vanilla/PlaybackService.java index 4f2f48c5..f46c49f4 100644 --- a/src/ch/blinkenlights/android/vanilla/PlaybackService.java +++ b/src/ch/blinkenlights/android/vanilla/PlaybackService.java @@ -43,6 +43,7 @@ import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; +import android.media.AudioDeviceInfo; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Build; @@ -65,6 +66,7 @@ import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; +import java.util.Arrays; import java.util.ArrayList; @@ -967,21 +969,24 @@ public final class PlaybackService extends Service @SuppressWarnings("deprecation") private boolean isSpeakerOn() { - // Android seems very intent on making this difficult to detect. In - // Android 1.5, this worked great with AudioManager.getRouting(), - // which definitively answered if audio would play through the speakers. - // Android 2.0 deprecated this method and made it no longer function. - // So this hacky alternative was created. But with Android 4.0, - // isWiredHeadsetOn() was deprecated, though it still works. But for - // how much longer? - // - // I'd like to remove this feature so I can avoid fighting Android to - // keep it working, but some users seem to really like it. I think the - // best solution to this problem is for Android to have separate media - // volumes for speaker, headphones, etc. That way the speakers can be - // muted system-wide. There is not much I can do about that here, - // though. - return !mAudioManager.isWiredHeadsetOn() && !mAudioManager.isBluetoothA2dpOn() && !mAudioManager.isBluetoothScoOn(); + // Devices we consider to not be speakers. + final Integer[] headsetTypes = { AudioDeviceInfo.TYPE_BLUETOOTH_A2DP, AudioDeviceInfo.TYPE_BLUETOOTH_SCO, + AudioDeviceInfo.TYPE_WIRED_HEADSET, AudioDeviceInfo.TYPE_WIRED_HEADPHONES, + AudioDeviceInfo.TYPE_USB_HEADSET }; + boolean result = true; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + AudioDeviceInfo[] devices = mAudioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS); + for (AudioDeviceInfo device: devices) { + if (Arrays.asList(headsetTypes).contains(device.getType())) { + result = false; + break; + } + } + } else { + result = !mAudioManager.isWiredHeadsetOn() && !mAudioManager.isBluetoothA2dpOn() && !mAudioManager.isBluetoothScoOn(); + } + + return result; } /**