SoFunction
Updated on 2025-04-08

Android method to detect whether the headset is inserted

AudioManager has this method:
isWiredHeadsetOn();
If the headset is inserted, it returns true, otherwise false;
Of course, you need to add permission, otherwise it will always return false.
<uses-permission android:name=".MODIFY_AUDIO_SETTINGS" />
At first I've been chasing the source code for a long time. I discovered the process of real-time detection of the plug-in and unplugging of the headphones, but it was not very helpful to my needs.
Real-time detection of headphone insertion and removal:
Whenever the headset is plugged in and unplugged, the system will send an Intent broadcast.
Therefore, you only need to use a receiver to intercept the broadcast intent (the action obtained is: ".HEADSET_PLUG").
This receiver must be registered with code, and cannot be written in the manifest by writing to memory.
Implement the detection of headphone insertion and removal under Android, that is, establish a Broadcast Receiver to monitor the ".HEADSET_PLUG" broadcast
But it is invalid to directly add a <receiver> tag to it, such as:
[html]
Copy the codeThe code is as follows:

<receiver android:name=".HeadsetPlugReceiver">
<intent-filter>
<action android:name=".HEADSET_PLUG" android:enabled="true"></action>
</intent-filter>
</receiver>

You will find that Receiver's onReceive event will never be triggered, and the solution is to manually write the code to register the broadcast.
First, create a subclass of BroadcastReceiver to listen for headphone insertion and removal:
[java]
Copy the codeThe code is as follows:

public class HeadsetPlugReceiver extends BroadcastReceiver {
private static final String TAG = "HeadsetPlugReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (("state")){
if (("state", 0) == 0){
(context, "headset not connected", Toast.LENGTH_LONG).show();
}
else if (("state", 0) == 1){
(context, "headset connected", Toast.LENGTH_LONG).show();
}
}
}
}

Then, register to listen to the broadcast in onCreate() in the Activity that needs to listen to the event, and do not forget to log out of listening to the broadcast in onDestroy():
[java]
Copy the codeThe code is as follows:

public class TestHeadSetPlugActivity extends Activity {
private HeadsetPlugReceiver headsetPlugReceiver;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView();
/* register receiver */
registerHeadsetPlugReceiver();
}
private void registerHeadsetPlugReceiver() {
headsetPlugReceiver = new HeadsetPlugReceiver();
IntentFilter intentFilter = new IntentFilter();
(".HEADSET_PLUG");
registerReceiver(headsetPlugReceiver, intentFilter);
}
@Override
public void onDestroy() {
unregisterReceiver(headsetPlugReceiver);
();
}
}

As mentioned above, you can detect the insertion and removal of the headphones.