From 49837033755dbfc9da951892a3a73c4ba4541602 Mon Sep 17 00:00:00 2001 From: Sam Bazley Date: Tue, 4 Jan 2022 11:19:52 +0000 Subject: [PATCH] Android: Detect output change with ACTION_AUDIO_BECOMING_NOISY Improves the changes made in 57687779befd796b79b1a569daf9e48eac3aea26 by using AudioManager.ACTION_AUDIO_BECOMING_NOISY rather than listening for wired headset unplug events or Bluetooth headset disconnect events. This method is more flexible, allowing the feature to work on other types of audio output device, as well as Bluetooth devices that don't set their device class correctly. This change also has the benefit of being more responsive, pausing the audio before it is rerouted to the built-in speaker. https://developer.android.com/guide/topics/media-apps/volume-and-earphones --- android/AndroidManifest.xml | 3 --- android/src/Main.java | 21 +++++---------------- 2 files changed, 5 insertions(+), 19 deletions(-) diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml index c375aa58b..46533971c 100644 --- a/android/AndroidManifest.xml +++ b/android/AndroidManifest.xml @@ -17,8 +17,6 @@ - - - diff --git a/android/src/Main.java b/android/src/Main.java index 4f314f8aa..e40f03195 100644 --- a/android/src/Main.java +++ b/android/src/Main.java @@ -24,14 +24,13 @@ import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothClass; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; +import android.media.AudioManager; import android.os.Build; import android.os.IBinder; import android.os.PowerManager; @@ -200,24 +199,14 @@ public class Main extends Service implements Runnable { return; IntentFilter filter = new IntentFilter(); - filter.addAction(Intent.ACTION_HEADSET_PLUG); - filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); - filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); + filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - if (!mPauseOnHeadphonesDisconnect) { + if (!mPauseOnHeadphonesDisconnect) return; - } - - if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) { - if (intent.hasExtra("state") && intent.getIntExtra("state", 0) == 0) - pause(); - } else { - BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); - if (device.getBluetoothClass().hasService(BluetoothClass.Service.AUDIO)) - pause(); - } + if (intent.getAction() == AudioManager.ACTION_AUDIO_BECOMING_NOISY) + pause(); } }, filter);