Recently, I have been studying how to use headphones for some control operations, which naturally involves how to check whether the earphones are inserted. After some queries and experiments, I will summarize the following:
1. Principle:
In fact, the android system will send broadcasts when the earphones are inserted and pulled out. Therefore, to detect the status of the earphones, you only need to register the broadcastreceiver to respond to the status.
The broadcast name is:Android. Intent. Action. headset_plug
Note: add the response permission in manifest. xml:
<Uses-Permission Android: Name = "android. Permission. modify_audio_settings"/>
Note: broadcast must be dynamically registered in the Java file.
2. Code
/*** Created by: Alex */package COM. alex. erji; import android. app. activity; import android. content. broadcastreceiver; import android. content. context; import android. content. intent; import android. content. intentfilter; import android. OS. bundle; import android. widget. toast; public class mainactivity extends activity {@ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); // intentfilter bound to the broadcast response intentfilter = new intentfilter (); intentfilter. addaction ("android. intent. action. headset_plug "); headsetreceiver = new headsetreceiver (); registerreceiver (headsetreceiver, intentfilter );} // custom broadcast receiver public class headsetreceiver extends broadcastreceiver {@ overridepublic void onreceive (context, intent) {If (intent. hasextra ("state") {If (0 = intent. getintextra ("State", 0) {toast. maketext (context, "headset not inserted", toast. length_short ). show ();} else if (1 = intent. getintextra ("State", 0) {toast. maketext (context, "headset inserted", toast. length_short ). show ();}}}}}
After normal operation, the system will remind you that the headset is inserted. When you unplug the headset, the system will remind you that the headset is not inserted ".