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
Packagecom.yydcdut.ear;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.content.IntentFilter;ImportAndroid.view.Menu;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); //filter to bind a response to a broadcastIntentfilter Intentfilter =NewIntentfilter (); Intentfilter.addaction ("Android.intent.action.HEADSET_PLUG"); Headsetreceiver Headsetreceiver=NewHeadsetreceiver (); Registerreceiver (Headsetreceiver, Intentfilter); } //self-defined broadcast receivers Public classHeadsetreceiverextendsBroadcastreceiver {@Override Public voidOnReceive (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 is plugged in", Toast.length_short). Show (); } } } } }
I'm the dividing line of the king of the Land Tiger.
Source code: HTTP://PAN.BAIDU.COM/S/1DD1QX01
Headphones. zip