Use AudioDeviceInfo on newer android devices to detect if headphones or headsets are connected.

This commit is contained in:
Adrian Ulrich committed 2017-12-11 19:38:41 +01:00
1 parent 7f1e079139
commit 9c6c18912f
1 file changed
+20 -15
@@ -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;
}
/**