Audiomanager has this method:
Iswiredheadseton ();
Returns true if the headset is inserted, otherwise false;
Of course, to add a permission, or always return false.
<uses-permission android:name= "Android.permission.MODIFY_AUDIO_SETTINGS"/>
I started chasing after a long time source code. The process of detecting headphone inserts and unplugging was found in real time, but not very helpful to my needs.
Real-time detection of headphone insertion and pull-out:
Every time you insert and unplug headphones, the system sends intent broadcasts,
So, just use a receiver to take this broadcast intent (get the action is: "Android.intent.action.HEADSET_PLUG") intercepted.
This receiver must be registered in code, not written in manifest.
Detect headphone inserts and unplug under Android, and create a broadcast Receiver to monitor "Android.intent.action.HEADSET_PLUG" broadcasts
But adding a <receiver> tag directly to the androidmanifest.xml is not valid, such as:
[HTML]
Copy Code code as follows:
<receiver android:name= ". Headsetplugreceiver ">
<intent-filter>
<action android:name= "Android.intent.action.HEADSET_PLUG" android:enabled= "true" ></action>
</intent-filter>
</receiver>
You will find that the receiver OnReceive event will never be triggered, and the solution is to manually write code to register the broadcast.
First, create a broadcastreceiver subclass that listens for headphones to insert and unplug:
[Java]
Copy Code code as follows:
public class Headsetplugreceiver extends Broadcastreceiver {
private static final String TAG = "Headsetplugreceiver";
@Override
public void OnReceive (context context, Intent Intent) {
if (Intent.hasextra ("state")) {
if (Intent.getintextra ("state", 0) = = 0) {
Toast.maketext (context, ' headset not connected ', Toast.length_long). Show ();
}
else if (Intent.getintextra ("state", 0) = = 1) {
Toast.maketext (Context, "Headset connected", Toast.length_long). Show ();
}
}
}
}
Then, register to listen to the broadcast in OnCreate () in the activity that needs to listen for the event, and do not forget to log off listening to the broadcast in OnDestroy ():
[Java]
Copy Code code as follows:
public class Testheadsetplugactivity extends activity {
Private Headsetplugreceiver Headsetplugreceiver;
/** called the activity is a. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
/* Register Receiver * *
Registerheadsetplugreceiver ();
}
private void Registerheadsetplugreceiver () {
Headsetplugreceiver = new Headsetplugreceiver ();
Intentfilter intentfilter = new Intentfilter ();
Intentfilter.addaction ("Android.intent.action.HEADSET_PLUG");
Registerreceiver (Headsetplugreceiver, Intentfilter);
}
@Override
public void OnDestroy () {
Unregisterreceiver (Headsetplugreceiver);
Super.ondestroy ();
}
}
such as this can be implemented to detect headphones plugged in and unplugged.