1. earphone plugging
First, register the aggreger in oncreate,
registerReceiver(headSetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
Next, it is the receiving broadcast part:
Private Final broadcastreceiver headsetreceiver = new broadcastreceiver () {@ override public void onreceive (context, intent) {log. D (TAG, "into headsetreceiver! "); String action = intent. getaction (); If (action. equals (intent. action_headset_plug) {// headphone plugged if (intent. getintextra ("State", 0) = 1) {// do something log. D (TAG, "this is headphone plugged"); headsetstate. settext ("headset Detection: INSERTED"); // headphone unplugged} else {// do something log. D (TAG, "this is headphone unplugged"); headsetstate. settext ("earphone Detection: No insertion ");}}}};
2. earphone button Detection
/* Earphone buttons */Public Boolean onkeydown (INT keycode, keyevent event) {Switch (keycode) {Case keyevent. keycode_headsethook: // displaytoast ("Press: headset key"); headsetstate. settext ("headset Detection: insert, press the headset button"); break;} return true;} public Boolean onkeyup (INT keycode, keyevent event) {Switch (keycode) {Case keyevent. keycode_headsethook: // displaytoast ("pop-up: headset key"); headsetstate. settext ("headset Detection: insertion, headset button bounce"); break;} return true ;}
The headset buttons can be detected. Some people on the Internet say that the following method can be used to detect the headset buttons, and there are more than N reprinted. I tried... Hope that a successful buddy will give me a message after seeing it. Communication is very important...
You only need to add intent. action_media_button to the filter and then process final keyevent event = (keyevent) intent. getparcelableextra (intent. extra_key_event) in the onreceive function; If (event! = NULL & event. getaction () = keyevent. action_down) {// do something}
As mentioned above, I now understand that the concept of a priority for broadcasting and receiving is in it, and the hook is intercepted by the system's own broadcaster, after the application is used up, it is destroyed again. As a result, my application cannot listen to the hook button. As long as the priority of the Broadcast Reception is increased, the system will be 1000. My number is 1000 + 1. OK!