Reprint Please specify source: http://blog.csdn.net/fengyuzhengfan/article/details/46461253
when the media button of the headset is clicked, Android The system will issue a broadcast, the carrier of the broadcast a Action name is Media_button of the Intent . Listen to the broadcast to get a click event for the Headset media button on the phone.
in the Android there is a Audiomanager class that will maintain the Media_button broadcast, so to achieve the headset key monitoring needs to Audiomanager register a receiver to receive the headset key Click event:
Audiomanager Audiomanager = (audiomanager) context . Getsystemservice (Context.audio_service); ComponentName name = Newcomponentname (Context.getpackagename (), MediaButtonReceiver.class.getName ()); Audiomanager.registermediabuttoneventreceiver (name);
The prototype of this method is:
publicvoid registermediabuttoneventreceiver (pendingintent eventreceiver)
Added in API level
Registera component to be the sole receiver of Media_button intents. This was like registermediabuttoneventreceiver (android.content.ComponentName), but allows the buttons to go to any pendingintent. Note that you shouldonly use this form if you know you'll continue running for the full timeuntil unregistering the Pend Ingintent.
Parameters
|
Span lang= "en-US" style= "FONT-SIZE:12.0PT; font-family: Arial ">eventreceiver |
< Span lang= "en-US" style= "FONT-SIZE:12.0PT; font-family: Arial ">target that would receive media button intents. The pendingintent would be sent an action_media_button event When a Media button action occurs, with extra_key_event added and holding the key code of the media button that is pressed. |
from API Note that:
1 , Registers a Mediaobuttonreceviewith the Audiomanager object, making it a Media_button 's only receiver, that is, only I can receive, the other is not receiving this broadcast, otherwise we will receive a certain confusion ;
2 , the broadcast must be in Androidmanifest.xml file, or you won't be listening to the Media_button broadcast it.
Note that because when we signed up, Audiomanager Media key receiver, and the receiver is the only receiver of media keys, so to cancel the registration when the key is not used to listen:
Audiomanager Audiomanager = (audiomanager) context . Getsystemservice (Context.audio_service); ComponentName name = Newcomponentname (Context.getpackagename (), MediaButtonReceiver.class.getName ()); Audiomanager.unregistermediabuttoneventreceiver (name);
When the headset media key occurs when the Click event, the Android System will issue two broadcasts, the first time the button is pressed down, the second time to release the button, in order to be able to accurately know how many times the user clicked the media key, We only need to handle the Click event when the key is released:
KeyEvent keyevent = (keyevent) Intent.getparcelableextra (intent.extra_key_event); Get KeyEvent Object if (keyevent.getaction () = = keyevent.action_up) {//Handle click event here}
Here are some of the classes that are used to achieve the line control effect:
1. Headphone Line control management tool class Headsetutil :
Package Com.jph.lc;import Android.content.componentname;import Android.content.context;import Android.media.audiomanager;import android.util.log;/** * Headset Line control management Tool Class single example * @author JPH * @date 2015-6-9 PM 4:03:45 */public cl Headsetutil {private static headsetutil headsetutil;private onheadsetlistener Headsetlistener = null;public static He Adsetutil getinstance () {if (Headsetutil = = null) {Headsetutil = new Headsetutil ();} return headsetutil;} /** * Set up headphones click on the listener interface must be set before open this interface, otherwise invalid setting * @param headsetlistener */public void Setonheadsetlistener (Onheadsetlistener Headsetlistener) {this.headsetlistener = Headsetlistener;} /** * For Media_button intention to register the receiver (register to turn on the headset line control monitoring, be sure to set the interface after listening to call this method, otherwise the interface is not valid) * @param context */public void open (context context) {I F (headsetlistener==null) {throw new IllegalStateException ("Please set Headsetlistener");} Audiomanager Audiomanager = (audiomanager) context.getsystemservice (Context.audio_service); ComponentName name = new ComponentName (Context.getpackagename (), mediabuttonreceiveR.class.getname ()); Audiomanager.registermediabuttoneventreceiver (name); LOG.I ("Ksdinf", "Open");} /** * Turn off the headset line control monitor * @param context */public void Close (context context) {Audiomanager Audiomanager = (audiomanager) context.g Etsystemservice (Context.audio_service); ComponentName name = new ComponentName (Context.getpackagename (), MediaButtonReceiver.class.getName ()); Audiomanager.unregistermediabuttoneventreceiver (name);} /** * Remove Headset Single-click Listener interface */public void Delheadsetlistener () {this.headsetlistener = null;} /** * Get headphones Click Double-tap Interface * * @return */protected onheadsetlistener Getonheadsetlistener () {return headsetlistener;} /** * Headphone button single-click Monitor */public interface Onheadsetlistener {/** * Click Trigger, Main thread. This interface is really triggered after the click Operation for 1 seconds because it is necessary to determine whether to still hear the click in 1 seconds, some words that is double-click the */public void OnClick ();/** * Double-click Trigger, this interface in the main thread, you can safely use */public void OnDoubleClick ();/** * Triple combo */public void Onthreeclick ();}} This class is primarily responsible for registering the media key receiver and customizing the settings of the media key callback listener. The class contains aOnheadsetlistenerinterface, in which theOnClick (),OnDoubleClick (),Onthreeclick ()Three methods are recalled when the Click event, double-click event, and triple combo event occur. It should be noted that clicking and double-clicking events will have 1 seconds of delay, this is because in this1seconds to listen if there is a reason why the click occurred, of course, this1snor is it absolute, and you can customize events according to the actual business needs. The class described below will solve the principle of cool dog line control.
2. Headset Media key broadcast receiver mediabuttonreceiver:
Package Com.jph.lc;import Java.util.timer;import Java.util.timertask;import android.content.BroadcastReceiver; Import Android.content.context;import android.content.intent;import android.os.handler;import android.os.Message; Import Android.util.log;import android.view.keyevent;import com.jph.lc.headsetutil.onheadsetlistener;/** * MEDIA_ Button Headset Media key broadcast receiver * @author JPH * @Date2015-6-9 pm 8:35:40 */public class Mediabuttonreceiver extends BROADCASTRECEIVER{PR Ivate Timer timer = null;private Onheadsetlistener Headsetlistener = null;private static Mtask MyTimer = null;/** Click Count **/pr ivate static int Clickcount;public mediabuttonreceiver () {timer = new timer (true); This.headsetlistener = Headsetutil.getinstance (). Getonheadsetlistener ();} @Overridepublic void OnReceive (context context, Intent Intent) {log.i ("Ksdinf", "onreceive"); String intentaction = Intent.getaction (); if (Intent.ACTION_MEDIA_BUTTON.equals (intentaction)) {KeyEvent keyevent = (keyevent) Intent.getparcelableextra (inten T.Extra_key_event); Gets the KeyEvent object if (Headsetlistener! = null) {try {if (keyevent.getaction () = = keyevent.action_up) { if (clickcount==0) {//click clickcount++; MyTimer = new Mtask (); Timer.schedule (mytimer,1000);} else if (clickcount==1) {//double-click clickcount++;} else if (clickcount==2) {//Triple combo Clickcount=0;mytimer.cancel (); Headsetlistener.onthreeclick ();} }} catch (Exception e) {}}} abortbroadcast ();//stop broadcasting (do not allow other programs to receive this broadcast, avoid interference)}/** * timer, for 1 seconds delay, to determine if double-click and Triple Combo */class Mtask extends timertask{@Overridepublic void run () {try {if (clickcount==1) {mhhandler.sendemptymessage (1);} else if (clickcount==2) {mhhandler.sendemptymessage (2);} clickcount=0;} catch (Exception e) {///todo:handle exception}}};/** * The purpose of this handle is primarily to trigger the interface in the main thread *, and to put the interface on the main thread for security reasons trigger */handler Mhhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); if (msg.what==1) {// Click Headsetlistener.onclick ();} else if (msg.what==2) {//DualHit Headsetlistener.ondoubleclick ();} else if (msg.what==3) {//Triple combo Headsetlistener.onthreeclick ();}}};} This class is primarily responsible for receiving the Click events of media cases issued by the system and handling the click events accordingly to achieve the effect of clicking, double clicking, triple Combo. It should be noted that the class will be instantiated to get onheadsetlistener Listener, so before calling the open method of the Headsetutil class, set the Onheadsetlistener , otherwise the media key event will not be processed.
There is a name in the class named Mtask internal class, which is a timed task that analyzes whether a double-click and triple-combo will occur in the specified time.
In addition, there is one in this class MyHandler object that is the object in order for the callback listener to occur in the UI thread, to facilitate UI the update.
3. The listener uses the class mainactivity:
Package Com.jph.lc;import Android.app.activity;import Android.os.bundle;import android.util.log;import Android.widget.textview;import com.jph.lc.headsetutil.onheadsetlistener;/** * Headphone Cable Control example, Bluetooth headset button monitoring (cool dog Line control effect) * @author JPH * @Date2015-6-10 a.m. 9:49:02 */public class Mainactivity extends Activity {TextView txt = null; @Overrideprotected void Oncre Ate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); txt = ( TextView) Findviewbyid (R.id.text); Headsetutil.getinstance (). Setonheadsetlistener (Headsetlistener); Headsetutil.getinstance (). open (this);} @Overrideprotected void OnDestroy () {Super.ondestroy (); Headsetutil.getinstance (). Close (this);} Onheadsetlistener Headsetlistener = new Onheadsetlistener () {@Overridepublic void OnDoubleClick () {Txt.settext ("double-click"); LOG.I ("Ksdinf", "Double-click");} @Overridepublic void OnClick () {Txt.settext ("click"); LOG.I ("Ksdinf", "click");} @Overridepublic void Onthreeclick () {Txt.settext ("triple combo"); LOG.I ("Ksdinf", "triple Combo");}};}
This class cited to introduce the use of media key monitoring.
source Download:http://download.csdn.net/detail/fengyuzhengfan/8797357
GitHub:Https://github.com/crazycodeboy/HeadSetControl
Android Headset Line control detailed, Bluetooth headset button monitoring (cool dog line control effect)