Principle
In fact, the Android system will send the broadcast when the headset is plugged in and unplugged, so we want to detect the headset's status only needs to register the response of the broadcastreceiver, the status of the response to the judgment is OK.
The name of the broadcast is called:Android.intent.action.HEADSET_PLUG
Code
Package Com.yydcdut.ear;import Android.os.bundle;import Android.app.activity;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.view.menu;import Android.widget.toast;public class MainActivity extends Activity {@Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Filter that binds the response to the broadcast intentfilter intentfilter = new Intentfilter (); Intentfilter.addaction ("Android.intent.action.HEADSET_PLUG"); Headsetreceiver headsetreceiver = new Headsetreceiver (); Registerreceiver (Headsetreceiver, Intentfilter); }//self-defined broadcast receiver public class Headsetreceiver extends Broadcastreceiver {@Override public void OnReceive (context context, Intent Intent) {if (Intent.hasextra ("state")) {if (0 = = IntenT.getintextra ("state", 0)) {toast.maketext (context, "headset not plugged in", Toast.length_short). Show (); } else if (1 = = Intent.getintextra ("state", 0)) {toast.maketext (context, "headset inserted", Toast.lengt H_short). Show (); } } } } }