Home:ALL Converter>Check if headset is connected on different API levels

Check if headset is connected on different API levels

Ask Time:2018-09-01T19:30:41         Author:Sasha Shpota

Json Formatter

I have an application that targets API Level 19+. I need to check if headset is connected (either of wired or bluetooth).

I see that AudioManager.isWiredHeadsetOn() is deprecated starting from API Level 16 and the documentation offers to use AudioManager.getDevices() which was introduced only starting from API Level 23.

Question: What is the proper way to check if headset is connected for API levels 16 - 22?

Note: I know that I can still use the deprecated method, but I don't want to. If they deprecated it they should have introduced a replacement API (which I though can't find).

Author:Sasha Shpota,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/52127683/check-if-headset-is-connected-on-different-api-levels
spartygw :

You need to listen for ACTION_HEADSET_PLUG which fires on headset events and also apparently fires periodically even when nothing changes.\n\nFrom my existing code I have this in onCreate of my main service:\n\n // listen for headphone events so we can auto switch the audio output when headphones are plugged in\n myHeadphoneMonitor = new HeadphoneMonitor();\n android.content.IntentFilter headphone_filter = new \n android.content.IntentFilter(Intent.ACTION_HEADSET_PLUG);\n registerReceiver(myHeadphoneMonitor, headphone_filter);\n\n\nAnd my monitor looks like this:\n\n package com.myname.foo;\n\n import android.content.BroadcastReceiver;\n import android.content.Context;\n import android.content.Intent;\n import android.util.Log;\n import android.os.Message;\n\n\n public class HeadphoneMonitor extends BroadcastReceiver\n {\n public boolean headphonesActive=false;\n\n @Override\n public void onReceive(final Context context, final Intent intent)\n {\n if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG))\n {\n int state = intent.getIntExtra(\"state\", -1);\n switch (state) {\n case 0:\n Log.d(\"HeadphoneMonitor\", \"Headset is unplugged\");\n headphonesActive=false;\n break;\n case 1:\n Log.d(\"HeadphoneMonitor\", \"Headset is plugged in\");\n headphonesActive=true;\n break;\n default:\n Log.d(\"HeadphoneMonitor\", \"I have no idea what the headset state is\");\n break;\n }\n\n // push this event onto the queue to be processed by the Handler\n Message msg = MyApp.uiHandler.obtainMessage(MyApp.HEADPHONE_EVENT);\n MyApp.uiHandler.sendMessage(msg);\n }\n }\n }\n\n\nNothing is needed in the manifest to listen for this broadcast event.",
2018-09-26T14:37:31
yy